Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript add properties to Vue library definitions

I use vue which includes types. However I want to use some properties that are added by certain plugins.

e.g.

Vue.$ga
Vue.$router

Typescript complains that Vue does not have those properties. Can I somehow add those globally to the Vue definition?

like image 299
Chris Avatar asked Jan 03 '18 11:01

Chris


2 Answers

Yes you can:

import Vue from 'vue'

declare module 'vue/types/vue' {
    interface VueConstructor {
        $ga: any; // define real typings here if you want
        $router: any;
    }
}

You can find more info specific to Vue here

like image 125
Aleksey L. Avatar answered Nov 13 '22 18:11

Aleksey L.


On main.ts, add:

Vue.prototype.$ga = 'your ga service'

Create a definition file 'my-file.d.ts' on your project /src folder.

import Vue, { VueConstructor } from 'vue';

declare module 'vue/types/vue' {

    interface Vue {
        $ga: any;
    }

    interface VueConstructor {
        $ga: any;
    }
}

declare module 'vue/types/options' {
    interface ComponentOptions<V extends Vue> {
        $ga?: any;
    }
}

Now you can use it inside your component by simple doing:

console.log(this.$ga); // your ga service
like image 5
Renatex Avatar answered Nov 13 '22 18:11

Renatex