Javascript is required
Mokkapps LogoMichael Hoffmann

Vue Tip: Typing Template Refs With TypeScript

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Sep 3, 2022
1 min read
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:

<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.