Javascript is required
·
0 min read

Vue Tip: Typing Template Refs With TypeScript

Vue Tip: Typing Template Refs With TypeScript Image

Template refs only exist after the component is mounted. Thus, it’s necessary to type template refs with a union type that includes the DOM element type as well as null:

1<template>
2  <textarea ref="textareaRef" />
3</template>
4
5<script setup lang="ts">
6import { ref, onMounted } from 'vue'
7
8const textareaRef = ref<HTMLTextAreaElement | null>(null)
9
10onMounted(() => {
11  textareaRef.value?.focus()
12})
13</script>

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.