Back
VueMediumNew

How do you properly type a `ref` in TypeScript, especially for complex or nullable values?

Generic type argument to ref()

Ideal Answer

ref() infers the type from its initial value, but for cases like a nullable DOM element or a union type, pass an explicit generic type:

JavaScript
import { ref } from 'vue'

const el = ref<HTMLInputElement | null>(null)
const status = ref<'idle' | 'loading' | 'error'>('idle')

interface User { id: number; name: string }
const user = ref<User | null>(null)

This is especially important for template refs pointing to DOM elements, since without an explicit type, TypeScript can't know what element type to expect.