简体   繁体   中英

Vue3 Typescript declaration file

I have a Vue3 plugin in js, like that:

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

It is in index.js, and will be invoked by app.use. For TS projects I need to create a type declaration. I found vue/types/plugin in the vue package with an interface for the object and a type for the install method. 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?

As of Vue 3.1.1, App.use() allows the options argument to be any , which seems to prevent augmenting its type declaration. That is, this module augmentation does not override the original App.use() (perhaps because any supercedes 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:

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:

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

demo

I also submitted a PR to vue-next . If it gets merged, you wouldn't need module augmentation, as the options type would be automatically inferred.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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