Home » vue » VueJS – Giving refs on this.$refs a type to remove Typescript errors

VueJS – Giving refs on this.$refs a type to remove Typescript errors

Posted by: admin November 26, 2021 Leave a comment

Questions:

In rough pseudo code, if I do something like this:

<v-menu
  ref="dmenu"
  other="stuff here"
  @change="save"
>

And then reference it later:

save(val: string) {
  this.$refs.dmenu.save(val)
}

I get an error “Property ‘save’ does not exist on type ‘Element'”

Is it possible to declare that items on this.$refs. are of type any?

This works:

save(val) {
  const m = this.$refs.dmenu as any
  m.save(val)
}

But it seems like an extra line of code just to keep Typescript happy.

Answers:

You have to either specify the type of element as VMenu and then access the method on it otherwise you have to specify the marked ref as any.

(this.$refs.dmenu as any).save(val)