【问题标题】:Vue3 Typescript declaration fileVue3 Typescript 声明文件
【发布时间】:2021-03-25 04:07:14
【问题描述】:

我在 js 中有一个 Vue3 插件,像这样:

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

它在 index.js 中,将由 app.use 调用。 对于 TS 项目,我需要创建一个类型声明。我在 vue 包中找到了 vue/types/plugin,其中包含对象的接口和安装方法的类型。但是我不知道如何将其应用于我的插件。 d.ts 文件中需要包含什么内容,以便 typescript 编译器知道 myPlugin 应该是 PluginObject 类型?

【问题讨论】:

标签: typescript vue.js vuejs3


【解决方案1】:

从 Vue 3.1.1 开始,App.use() 允许 options 参数为 any,这似乎阻止了增加其类型声明。也就是说,这个模块扩充不会覆盖原来的App.use()(可能是因为any取代了MyPluginOptions):

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

目前唯一的解决方法似乎是直接编辑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;

然后将当前的App.use() 替换为:

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

demo

我还提交了PR to vue-next。如果它被合并,您将不需要模块扩充,因为 options 类型将被自动推断。

【讨论】:

    猜你喜欢
    • 2016-09-27
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 2017-08-15
    • 1970-01-01
    • 2018-03-11
    • 2019-04-18
    相关资源
    最近更新 更多