jogarcia
jogarcia

Reputation: 2752

Call plugin object from component in Vue.js 2 with typescript

I created a plugin object for the regex I use in my app so I can use them in a global way. Something like this:

import Vue from "vue";

Vue.prototype.$regex = { 
  //isEmail function here
}

In javascript this code works. However in my new typescript project once I do:

methods: {
  isEmail(string: string): boolean {
    return this.$regex.isEmail(string)
  }
}

I get:

Property '$regex' does not exist on type 'CombinedVueInstance<Vue...

What's the correct way of using my plugin in a Vue.js 2 with typescript project?

Upvotes: 0

Views: 118

Answers (1)

I think, error happens because typescript does not know about your $regex in Vue's object prototype.

You can create file that will be included by typescript, for example types.d.ts in src directory, and put you type definition of $regex

import Vue from "vue";

declare module 'vue/types/vue' {
  export interface Vue {
    $regex: { isEmail: (some: string) => bool }
  }
}

ref: https://github.com/vuetifyjs/vuetify/blob/648799021a890f652f6eb6dd96713cb811c3efa6/packages/vuetify/types/index.d.ts#L60

Upvotes: 1

Related Questions