【问题标题】:How to extend VueConfiguration? I.e. how to extend existing interface?如何扩展 VueConfiguration? IE。如何扩展现有接口?
【发布时间】:2018-08-22 09:44:30
【问题描述】:

看起来很容易,但我很困惑。

假设我想将server 对象添加到Vue.config。 这是 Vue 的打字稿定义 - https://github.com/vuejs/vue/blob/dev/types/vue.d.ts#L121。所以我们需要扩展 VueConfiguration 接口 - https://github.com/vuejs/vue/blob/dev/types/vue.d.ts#L67

我尝试创建 index.d.ts 文件:

/// <reference path="../node_modules/vue/types/vue.d.ts" />

export interface VueConfiguration {
    server: {
        user: string;
    }
}

src/ 目录中,这无济于事。

尝试将此代码添加到 main.ts 文件中:

declare interface VueConfiguration {
  server: {
      blockchain: string;
  };
};

当我这样做时:

Vue.config.server.user = 'http://127.0.0.1:8082'

我收到错误“VueConfiguration”类型上不存在属性“服务器”

那么我做错了什么?

【问题讨论】:

    标签: typescript vue.js interface vuejs2


    【解决方案1】:

    我不知道修改现有界面的方法。相反,您应该创建一个扩展旧接口的新接口,然后在您的对象上使用类型断言,让 TS 编译器知道这些附加属性。

    export interface MyVueConfiguration extends VueConfiguration {
        server: {
            user: string;
        }
    }
    
    ...
    
    (Vue.config as MyVueConfiguration).server.user = 'http://127.0.0.1:8082'
    

    【讨论】:

    • 谢谢。这是一种方法,但使用我自己的界面,我需要手动修补 new Vue({}) 请求,因为他们无论如何都会使用 VueConfiguration。似乎 vue 还没有真正准备好打字。
    猜你喜欢
    • 1970-01-01
    • 2012-09-01
    • 2022-01-14
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 2020-09-28
    相关资源
    最近更新 更多