TypeScript with Vue

Intermediate · 13 min

Type-checking SFCs with vue-tsc, then typing props, emits, v-model, template refs, provide/inject, and generic components in script setup.

Before thisscript setup and compiler macrosTemplate refs and defineExposePinia setup stores and plugins

Program With Erik · 13 min

TypeScript with Vue

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Program With ErikReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • The plain TypeScript compiler cannot read a .vue file, so Vue projects type-check with vue-tsc, a wrapper around tsc that understands single-file components, and get editor support from the official Vue language tools (the project formerly called Volar).
  • Type-based declarations are the preferred style in script setup: defineProps<{...}>() and defineEmits<{...}>() take a type argument, and the compiler generates the runtime props and emits options from it.
  • Vite strips types without checking them, so a type error never stops the dev server; type-checking is a separate step you run in your editor, in a script, and in CI.
  • defineModel<T>(), useTemplateRef<T>(), and InjectionKey<T> extend the same idea to two-way bindings, template refs, and provide/inject, so the values that flow between components carry their types with them.
  • A generic component declares its type parameter with the generic attribute on the script setup tag, which lets a list or table component infer the item type from the props a parent passes in.

The problem: tsc cannot read a .vue file

A single-file component is three languages in one file. The TypeScript compiler only understands .ts files, so if you run tsc over a Vue project it either ignores your components or fails to resolve import Card from './Card.vue'. And even if it could read the <script> block, half the interesting code lives in the <template>, where a typo like {{ user.nmae }} is still a type error that nothing would catch.

Vue’s answer is a dedicated set of language tools. They turn each .vue file into a virtual TypeScript file, template expressions included, and hand that to the real TypeScript compiler. Two tools come out of that project:

  • vue-tsc, a command-line wrapper around tsc that type-checks .vue files. A project created with npm create vue@latest and TypeScript enabled already has a type-check script that runs it.
  • The “Vue - Official” editor extension (the project used to be called Volar), which gives you autocomplete, go-to-definition, and red squiggles inside templates.
{
  "scripts": {
    "dev": "vite",
    "build": "run-p type-check \"build-only {@}\" --",
    "type-check": "vue-tsc --build"
  }
}

One thing to internalise early: Vite does not type-check. It strips types and moves on, which is why the dev server is fast and why a type error never stops your app from loading. Types are enforced by your editor while you write, and by vue-tsc in your build script and CI. If you skip that step, TypeScript in a Vue project is just decoration. The type system itself (unions, generics, narrowing) is taught in the TypeScript roadmap; this lesson covers only what Vue adds on top.

Typing props

In <script setup lang="ts">, the preferred way to declare props is to pass a type to defineProps. The compiler reads that type and generates the runtime props option, so you write the shape once.

<script setup lang="ts">
interface Props {
  title: string
  size?: 'sm' | 'md' | 'lg'
  tags?: string[]
}

const { title, size = 'md', tags = () => [] } = defineProps<Props>()
</script>

<template>
  <h2 :class="`title-${size}`">{{ title }}</h2>
</template>

Defaults deserve a note because the syntax changed. Since Vue 3.5, destructuring the result of defineProps stays reactive (the compiler rewrites size to props.size behind the scenes), so plain JavaScript defaults work. Code written for 3.3 and 3.4, like the video’s, uses withDefaults, which is still supported:

const props = withDefaults(defineProps<Props>(), {
  size: 'md',
  tags: () => [],
})

You can import the Props interface from another file. The compiler resolves it, though it can’t evaluate every advanced type: a conditional type at the top level of the props type won’t compile, because the compiler needs to know the concrete list of prop keys to generate the runtime option.

Typing emits and v-model

defineEmits takes a type too. Since Vue 3.3 the shortest form maps each event name to a tuple of its arguments:

const emit = defineEmits<{
  select: [id: number]
  'update:filter': [value: string, source: 'input' | 'reset']
}>()

emit('select', 42)       // ok
emit('select', '42')     // type error: string is not assignable to number

The parent gets the benefit too: @select="(id) => ..." infers id as a number.

For two-way binding, defineModel (stable since Vue 3.4) declares the prop and the update event in one line, and it takes a type argument:

const query = defineModel<string>({ required: true })
const page = defineModel<number>('page', { default: 1 })

query is a Ref<string>; writing to it emits update:modelValue for you.

Template refs, provide/inject, and stores

Values that cross component boundaries without going through props need types attached explicitly, because Vue has nothing to infer them from.

Template refs. useTemplateRef (Vue 3.5) takes the element or component type. The value is null until the component mounts, so the type includes null and you have to check it:

import { onMounted, useTemplateRef } from 'vue'
import ConfirmDialog from './ConfirmDialog.vue'

const input = useTemplateRef<HTMLInputElement>('search')
const dialog = useTemplateRef<InstanceType<typeof ConfirmDialog>>('dialog')

onMounted(() => {
  input.value?.focus()
  dialog.value?.open() // only works if ConfirmDialog calls defineExpose({ open })
})

Provide/inject. A string key gives you unknown on the injecting side. An InjectionKey<T>, which is a typed Symbol, ties both ends to the same type:

// keys.ts
import type { InjectionKey, Ref } from 'vue'
export const ThemeKey: InjectionKey<Ref<'light' | 'dark'>> = Symbol('theme')

// in a descendant
const theme = inject(ThemeKey) // Ref<'light' | 'dark'> | undefined

Pinia. Setup stores are ordinary functions returning refs, computeds, and functions, so TypeScript infers the store’s type with no annotations. That is a big part of why the setup-store style pairs well with TypeScript.

Generic components

Some components don’t care what they hold: a select, a list, a data table. Typing their items as any throws away the parent’s information. A generic component declares a type parameter with the generic attribute:

<script setup lang="ts" generic="T extends { id: string | number }">
defineProps<{ items: T[] }>()
defineEmits<{ pick: [item: T] }>()
</script>

<template>
  <ul>
    <li v-for="item in items" :key="item.id" @click="$emit('pick', item)">
      <slot :item="item" />
    </li>
  </ul>
</template>

When a parent writes <PickList :items="users" @pick="onPick">, Vue infers T as the User type, so onPick and the scoped slot both get User, not unknown. React developers will recognise this as the Vue counterpart of a generic function component.

Typing events from the DOM

Native event handlers are where TypeScript asks for an annotation most often, because event.target is typed as the general EventTarget:

function onInput(event: Event) {
  const value = (event.target as HTMLInputElement).value
}

Most of the time v-model on the input makes this handler unnecessary.

What the video covers

Erik’s crash course is a chaptered tour of the script-setup TypeScript surface as of Vue 3.3: type-based defineProps, generic script setup, PropType for the runtime syntax, importing external types, withDefaults, typed defineEmits, typing ref/reactive/computed, and typing input and keyboard event handlers. It predates defineModel, reactive props destructure, and useTemplateRef, and it doesn’t cover the vue-tsc setup; the sections above fill those gaps. The two runners-up go further on generic components specifically.

Where this fits

TypeScript builds on the compiler macros from script setup and on template refs. Next: styling Vue components.

Check yourself

  1. 01Your project builds and runs fine in the browser, yet `npm run type-check` reports an error in a .vue file. How can both be true?

    Vite compiles TypeScript by stripping the types (via esbuild or a similar transpiler) without type-checking them, so a type error has no effect on the dev server or the bundle. Type-checking is a separate pass done by vue-tsc, which understands .vue files; that pass is the one reporting the error.

  2. 02What is the difference between `defineProps<{ size?: 'sm' | 'md' }>()` and `defineProps({ size: String })`?

    The first is a type-based declaration: the compiler reads the type and generates the runtime props option for you, and the prop is typed as the literal union `'sm' | 'md' | undefined`. The second is a runtime declaration: it only checks at runtime that the value is a string, and the inferred type is the wider `string | undefined`. The type-based form is the one the Vue docs recommend when using TypeScript.

  3. 03How do you give a prop a default value with type-based props in Vue 3.5 and later, and what did you use before that?

    From Vue 3.5 you destructure the props and use a JavaScript default, as in `const { size = 'md' } = defineProps<Props>()`, and the compiler keeps the destructured variable reactive. Before 3.5 you wrapped the call in `withDefaults(defineProps<Props>(), { size: 'md' })`, which still works.

  4. 04Why does a `<DataTable>` component benefit from `generic="T"` on its script setup tag?

    Without a type parameter its `rows` prop has to be typed as something loose like `unknown[]` or `any[]`, so the parent loses type information in slots and emitted events. With `generic="T"` and `rows: T[]`, Vue infers `T` from whatever array the parent passes, so a `row-click` event or a scoped slot receives the parent's real item type.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark