typeScript + vue3 边用边学,实例

201 阅读1分钟

1.如何在 window 对象上显式设置属性

问题:

image.png

解决方案,新建文件 window.d.ts,文件内容如下,

import type {
  LoadingBarProviderInst,
  DialogProviderInst,
  MessageProviderInst,
  NotificationProviderInst
} from 'naive-ui';

declare global {
  interface Window {
    $loadingBar?: LoadingBarProviderInst;
    $dialog?: DialogProviderInst;
    $message?: MessageProviderInst;
    $notification?: NotificationProviderInst;
  }
}

2.第三方包 无 typescript 声名文件

问题:

image.png

解决方案:新建文件 kurento-utils.d.ts,文件内容如下,

declare module 'kurento-utils' {
  export { WebRtcPeer } from 'kurento-utils';
  // WebRtcPeer 工程目录中需要用到的对象
}

3.ref 未指定类型

const currSelectOrg = ref(null);
const changeCurrentOrg = (org: TreeNode) => {
  currSelectOrg.value = org;
  emit('changeOrg', org);
};

问题:

image.png

解决方案:

const currSelectOrg = ref<TreeNode | null>(null);

4.{} 未知具体属性

问题:

image.png

解决方案,利用Record,声名对象属性类型及value类型

type ViewComponent = Record<string, () => Promise<Component>>
function getViewComponent() {
  const components:ViewComponent =  {}
  viewKeys.map(key => {
    const routeKey = key
      .replace(PREFIX, '')
      .replace(SUFFIX, '')
      .replace(new RegExp(PATH_SPLIT_MARK, 'g'), ROUTE_KEY_SPLIT_MARK)
    components[routeKey] = importViews[key]
  })
  return components
}