Vue Tip: Typing Template Refs With TypeScript

Michael Hoffmann
Sep 3, 2022
| 1 min read
| 121 views
Michael Hoffmann
Sep 3, 2022
1 min read
| 121 views
Template
Script

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:
<template> <textarea ref="textareaRef" /></template><script setup lang="ts">import { ref, onMounted } from 'vue'const textareaRef = ref<HTMLTextAreaElement | null>(null)onMounted(() => { textareaRef.value?.focus()})</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 Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter.
Vue Tip: Avoid Side Effects in Computed PropertiesAug 25, 2022
Vue Tip: Lifecycle Hooks for DebuggingSep 26, 2022
Show comments