·
1 min read

Vue Tip: Typing Template Refs With TypeScript

Vue Tip: Typing Template Refs With TypeScript Image

Since Vue 3.5, you can use the useTemplateRef() function to type template refs with TypeScript.

This function automatically infers the correct type for the template ref based on what element or component the matching ref attribute is used on:

Component.vue
<script setup> import { useTemplateRef, onMounted } from 'vue' const myInput = useTemplateRef('my-input') onMounted(() => { myInput.value.focus() }) </script> <template> <input ref="my-input" /> </template>

As you can see in the example above, the ref can only be accessed after the component is mounted. Therefore, we use the onMounted lifecycle hook to focus on the input element. In a template expression, myInput will be null on the first render because the element doesn't exist at that point.

If the auto-inference doesn't work as expected, you can provide a type argument to useTemplateRef() to specify the type explicitly:

const myInput = useTemplateRef<HTMLInputElement>(null)

Usage before 3.5

Before Vue 3.5, you had to use ref with a name that matches the template ref attribute's value. You need to cast the ref value to an explicit type via a generic argument:

Component.vue
<script setup lang="ts"> import { ref, onMounted } from 'vue' const textareaRef = ref<HTMLTextAreaElement | null>(null) onMounted(() => { textareaRef.value?.focus() }) </script> <template> <textarea ref="textareaRef" /> </template>

The initial ref value is null until the component is mounted or if the v-if directive unmounts the element. Therefore, we use optional chaining to access textareaRef.value.

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.