How to reach props via this using Typescript with Vue 2x

This article only describes this specific case, if you want to know how to set up Typescript for Vue this is a good source.

On a recent client project I had wanted to reach prop values of my component and needed to use this, but that causes errors:

// example
mounted(): void {
  this.interval = setInterval(() => {
    doSomething()
  }, 1000)
},

// error
Property 'interval' does not exist on type 'CombinedVueInstance<vue, {}, unknown, Readonly<{poll: Poll; radius: string;}>>'

This caused quite a bit of annoyance before I realised the simply fix.

The solution is just to add a placeholder in data so the Vue instance has this value on initialisation. This allows Typescript to know that the value does indeed exist on the instance.

export default Vue.extend({
  name: 'PollingComponent',
  data() {
    return {
      interval: 0 as any,
    }
  },
  mounted(): void {
    this.interval = setInterval(() => {
      doSomething()
    }, 1000)
  },
})

Now there’s some interesting browser compatibility problems regarding the type of an Interval. I found that it could be both a Timer or a Number depending on the browser. So in the end I just ended up using any. I can’t see any hard in that since it’s a Javascript function.

Happy coding!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s