前言:
一般在项目中都会封装自己的一些方法,比如把一些工具类方法放在util.ts里,比如:
// src/common/util.ts
function deepClone(obj, map) {
}
function debounce(fn, delay) {
}
然后在main.js里进行注册
// main.ts
import util from '@/common/util'
export function createApp() {
...
app.config.globalProperties.$util = util
return {
app
}
}
如果你用的是组合式api,那么直接导入即可;可如果是使用的选项式api,在组件内通过this.$util调用时,就会提示类型错误:
类型“CreateComponentPublicInstance<Readonly<ExtractPropTypes<Readonly<ComponentPropsOptions>>> & {
}, unknown, {
rectData: string; isShowPanel: boolean; ... 10 more ...; serverTime: string; }, ... 15 more ..., {
...; } | {
}>”上不存在属性“$util”。ts(2339)
这时需要用到Vue的ComponentCustomProperties
来为Vue实例加上我们自定义的类型提示。
解决方案
在src下创建一个shims-vue.d.ts
文件,加入以下代码:
import {
ComponentCustomProperties } from 'vue'
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$util: any
}
}
这时再去原来的位置看,红色波浪线应该已经没了,如果还有,可以尝试重启vscode。
这里我将$util
的类型注解为any
,这样可以应对任何情况,但不推荐这么做,不然就浪费ts的类型提示了。所以我们可以这样修改:
- 在src/下创建types文件夹,并创建一个util.d.ts文件,内容如下:
export type Util = {
formatRptType(name: string, type?: string): string
}
然后在shims-vue.d.ts
中将代码修改为:
import {
ComponentCustomProperties } from 'vue'
import {
Util } from '@/types/util'
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$util: Util
}
}
以后如若还有其它自定义的全局属性,都可以依葫芦画瓢添加提示。
这样,再去对应的调用处就可以看到提示了: