17

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?

1 Answer 1

17

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
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Does it matters where do i put this file in my project structure?
I typically put type declaration files in a types directory in the project's root folder.

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.