Using refs with Vue 3 + TypeScript + Options API

Viewed 1564

I am trying to understand the best way to use refs together with TypeScript and the Options API. In the docs they reference it like below, but that is without using TS. When it comes to TS, they only explain how to use it with Composition API.

When I use this.$refs.myRef it throws this error Object is of type 'unknown'.

I know that I can cast it and use it like this: (this.$refs.myRef as HTMLElement) but that I feel shouldn't be necessary to do for every ref every single time.

What is the correct way to use a reference with Options API + TS?

1 Answers

I created a shim like this:

shims-runtime-core.d.ts

import * as runtimeCore from '@vue/runtime-core'

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $refs: {
      [key: string]: HTMLElement|any,
    },
    // ... more stuff
  }
}

And then I can access the refs like normal.

Related