How to use Typescript with props in 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.

I recently had this issue in a client project. I wanted to use component properties with a shared Interface model, but using it directly as a type results in the error:

'Poll' only refers to a type, but is being used as a value here.

So how do you use a Typescript interface with your Vue component?

You make your type a function that returns the interface. Why this works I’m not quite sure of. But it does work.

Interface Poll {
  question: String,
}

export default Vue.extend({
  name: 'PollCard',
  props: {
    poll: {
      type: Object as () => Poll,
      default: {} as Poll
    }
  }
});

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