Baboo
Baboo

Reputation: 4278

How to access Vue prototype property from typescript component

I'm migrating my vuejs app to typescript for better maintanability. Here is my problem:

I created a TokenService to retrieve the admin's token from the local storage :

// token.service.js

/*
  Get the admin's token from localstorage.
  @return {object} The token
*/
getToken() {
  return localStorage.getItem("token")
}

To have the service available in all the components without having to import it in each one of them, I added the service to the Vue.prototype :

// main.js

Vue.prototype.$tokenService = TokenService

But when I try to access the this.$tokenService from my component AdminWorkerPage written in typescript, I get the error: TS2339: Property '$tokenService' does not exist on type 'AdminWorkerPage'.

// AdminWorkerPage.ts

import { Vue, Component, Prop } from 'vue-property-decorator'

@Component({})
export default class AdminWorkerPage extends Vue {

  broadcast(): Promise<void> {
    token: this.$tokenService.getToken() // <-- $tokenService used here !
    ...
  }
}

But when my file was written in javascript, I had no problem.

How can I tell the compiler that the property exists in the component?

Upvotes: 17

Views: 11947

Answers (1)

Brian Lee
Brian Lee

Reputation: 18197

You need to augment the Vue type:

// token-service.d.ts

import Vue from 'vue'
import TokenService from '../path/to/token-service'

declare module 'vue/types/vue' {
  interface Vue {
    $tokenService: TokenService
  }
}

Upvotes: 17

Related Questions