Foreword:
Generally, some of your own methods will be encapsulated in the project, such as putting some tool class methods in util.ts, such as:
// src/common/util.ts
function deepClone(obj, map) {
}
function debounce(fn, delay) {
}
Then register in main.js
// main.ts
import util from '@/common/util'
export function createApp() {
...
app.config.globalProperties.$util = util
return {
app
}
}
If you are using a combined API, you can just import it directly; but if you are using an optional API, when you call it through this.$util in the component, you will be prompted with a type error:
类型“CreateComponentPublicInstance<Readonly<ExtractPropTypes<Readonly<ComponentPropsOptions>>> & {
}, unknown, {
rectData: string; isShowPanel: boolean; ... 10 more ...; serverTime: string; }, ... 15 more ..., {
...; } | {
}>”上不存在属性“$util”。ts(2339)
At this time, we need to use Vue ComponentCustomProperties
to add our custom type hints to the Vue instance.
solution
Create a file under src shims-vue.d.ts
and add the following code:
import {
ComponentCustomProperties } from 'vue'
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$util: any
}
}
At this time, go to the original location to see, the red wavy line should be gone, if there is still, you can try to restart vscode.
Here I $util
annotate the type any
as so that it can handle any situation, but it is not recommended to do so, otherwise the type hint of ts will be wasted. So we can modify it like this:
- Create a types folder under src/, and create a util.d.ts file with the following content:
export type Util = {
formatRptType(name: string, type?: string): string
}
Then shims-vue.d.ts
modify the code in to:
import {
ComponentCustomProperties } from 'vue'
import {
Util } from '@/types/util'
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$util: Util
}
}
If there are other custom global attributes in the future, you can add hints according to the gourd painting.
In this way, you can see the prompt when you go to the corresponding call place: