我为我在应用程序中使用的正则表达式创建了一个插件对象,所以我可以以全局方式使用它们。像这样:
import Vue from "vue";
Vue.prototype.$regex = {
//isEmail function here
}
在javascript中,这段代码可以工作。然而,在我的新typescript项目中,一旦我这样做:
methods: {
isEmail(string: string): boolean {
return this.$regex.isEmail(string)
}
}
我:
Property '$regex' does not exist on type 'CombinedVueInstance<Vue...
在Vue.js 2与typescript项目中使用我的插件的正确方法是什么?
我认为,发生错误是因为typescript不知道你的$regex
在Vue的对象原型
你可以创建一个文件,将包含在typescript,例如types.d.ts
在src
目录,并把你的类型定义的$regex
import Vue from "vue";
declare module 'vue/types/vue' {
export interface Vue {
$regex: { isEmail: (some: string) => bool }
}
}
裁判:https://github.com/vuetifyjs/vuetify/blob/648799021a890f652f6eb6dd96713cb811c3efa6/packages/vuetify/types/index.d.ts L60