Javascript is required
Mokkapps Logo

Vue Tip: Typing Template Refs With TypeScript

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Sep 3, 2022
1 min read
|
437 views
Template
Script
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 content from me. Alternatively (or additionally), you can also subscribe to my newsletter.