I'm extending the default Vue object with
export default (Vue) => {
Object.defineProperties(Vue.prototype, {
$http: {
get () {
return axiosInstance
}
}
})
}
I'm using typescript and of course typescript doesn't like this. How can i create a project specific .d.ts file in such a way the vue typescript declaration is augmented with the above extension?
There is now excellent documentation regarding this on https://vuejs.org/v2/guide/typescript.html#Augmenting-Types-for-Use-with-Plugins:
Augmenting Types for Use with Plugins
Plugins may add to Vue’s global/instance properties and component options. In these cases, type declarations are needed to make plugins compile in TypeScript. Fortunately, there’s a TypeScript feature to augment existing types called module augmentation.
For example, to declare an instance property $myProperty with type string:
// 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 } }
After including the above code as a declaration file (like my-property.d.ts) in your project, you can use $myProperty on a Vue instance.
var vm = new Vue() console.log(vm.$myProperty) // This should compile successfully
You can also declare additional global properties and component options:
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 } }
The above declarations allow the following code to be compiled:
// Global property console.log(Vue.$myGlobal) // Additional component option var vm = new Vue({ myOption: 'Hello' })
Create a file with following content:
import {AxiosStatic} from 'axios';
declare module 'vue/types/vue' {
export interface Vue {
$http: AxiosStatic;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With