简体   繁体   English

Vue3 Typescript 声明文件

[英]Vue3 Typescript declaration file

I have a Vue3 plugin in js, like that:我在 js 中有一个 Vue3 插件,如下所示:

const myPlugin = {
    install(Vue, config) {
           // do something
    }
export default myPlugin;

It is in index.js, and will be invoked by app.use.它在 index.js 中,将由 app.use 调用。 For TS projects I need to create a type declaration.对于 TS 项目,我需要创建一个类型声明。 I found vue/types/plugin in the vue package with an interface for the object and a type for the install method.我在 vue package 中找到了 vue/types/plugin,其中有一个用于 object 的接口和一个用于安装方法的类型。 However I have no clue how to apply this to my plugin.但是我不知道如何将其应用于我的插件。 What needsto be inside the d.ts file so the typescript compiler knows that myPlugin is supposed to be of type PluginObject? d.ts 文件中需要什么,以便 typescript 编译器知道 myPlugin 应该是 PluginObject 类型?

As of Vue 3.1.1, App.use() allows the options argument to be any , which seems to prevent augmenting its type declaration.从 Vue 3.1.1 开始, App.use()允许options参数为any ,这似乎阻止了增加其类型声明。 That is, this module augmentation does not override the original App.use() (perhaps because any supercedes MyPluginOptions ):也就是说,这个模块扩充不会覆盖原来的App.use() (可能是因为any取代了MyPluginOptions ):

declare module '@vue/runtime-core' {
  interface App {
    use(plugin: MyPlugin, ...options: MyPluginOptions[]): this;
  }
}

It seems the only current workaround is to edit node_modules/@vue/runtime-core/dist/runtime-core.d.ts directly, adding a generic to Plugin_2 and PluginInstallFunction to enable typing the options argument:似乎当前唯一的解决方法是直接编辑node_modules/@vue/runtime-core/dist/runtime-core.d.ts ,向Plugin_2PluginInstallFunction添加一个泛型以启用输入options参数:

declare type Plugin_2<Option = any> = PluginInstallFunction<Option> & {
    install?: PluginInstallFunction<Option>;
} | {
    install: PluginInstallFunction<Option>;
};
export { Plugin_2 as Plugin }

declare type PluginInstallFunction<Option> = (app: App, ...options: Option[]) => any;

And then replacing the current App.use() with:然后将当前的App.use()替换为:

export declare interface App<HostElement = any> {
    use<Option>(plugin: Plugin_2<Option>, ...options: Option[]): this;
}

demo 演示

I also submitted a PR to vue-next .我还向vue-next提交了 PR If it gets merged, you wouldn't need module augmentation, as the options type would be automatically inferred.如果它被合并,您将不需要模块扩充,因为options类型将被自动推断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM