0

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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

This almost worked. There is only one detail missing. You have to import Vue in the file like so: import Vue from "vue"; otherwise it just won't work. That step isn't optional.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.