如何扩充Vue类并保持打字稿定义同步

pau*_*del 5 vue.js

我正在扩展默认的Vue对象

export default (Vue) => {
  Object.defineProperties(Vue.prototype, {
    $http: {
      get () {
        return axiosInstance
      }
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

我正在使用打字稿,当然打字稿不喜欢这样。如何以上述扩展名扩展vue打字稿声明,从而创建项目特定的.d.ts文件?

Mot*_*tin 8

现在在https://vuejs.org/v2/guide/typescript.html#Augmenting-Types-for-Use-with-Plugins上有关于此的出色文档:

与插件一起使用的增强类型

插件可能会添加到Vue的global / instance属性和组件选项。在这些情况下,需要使用类型声明来使插件在TypeScript中编译。幸运的是,有一个TypeScript功能可以扩展现有的类型,称为模块扩展。

例如,要声明类型为string的实例属性$ myProperty:

// 1. Make sure to import 'vue' before declaring augmented types
import Vue from 'vue'

// 2. Specify a file with the types you want to augment
//    Vue has the constructor type in types/vue.d.ts
declare module 'vue/types/vue' {
  // 3. Declare augmentation for Vue
  interface Vue {
    $myProperty: string
  }
}
Run Code Online (Sandbox Code Playgroud)

在将上述代码作为声明文件(如my-property.d.ts)包含在项目中之后,可以在Vue实例上使用$ myProperty。

var vm = new Vue()
console.log(vm.$myProperty) // This should compile successfully
Run Code Online (Sandbox Code Playgroud)

您还可以声明其他全局属性和组件选项:

import Vue from 'vue'

declare module 'vue/types/vue' {
  // Global properties can be declared
  // on the `VueConstructor` interface
  interface VueConstructor {
    $myGlobal: string
  }
}

// ComponentOptions is declared in types/options.d.ts
declare module 'vue/types/options' {
  interface ComponentOptions<V extends Vue> {
    myOption?: string
  }
}
Run Code Online (Sandbox Code Playgroud)

上面的声明允许编译以下代码:

// Global property
console.log(Vue.$myGlobal)

// Additional component option
var vm = new Vue({
  myOption: 'Hello'
})
Run Code Online (Sandbox Code Playgroud)


pau*_*del 7

创建一个具有以下内容的文件:

import {AxiosStatic} from 'axios';


declare module 'vue/types/vue' {
  export interface Vue   {
    $http: AxiosStatic;
  }
}
Run Code Online (Sandbox Code Playgroud)