Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 940
Baboo Avatar asked Dec 16 '18 01:12

Baboo


1 Answers

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
  }
}
like image 157
Brian Lee Avatar answered Nov 08 '22 13:11

Brian Lee