Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 87 ยท TypeScript and Quality

TypeScript with Vue

Use TypeScript in Vue 3 with script setup. Learn typed props and emits, typed refs and computed, generic components and how vue-tsc checks .vue files.

Vue 3 is written in TypeScript, and its APIs are designed so that types flow naturally from your code: a ref(0) is known to hold a number, a prop declared as string is a string in the template, and a typo in an emitted event name can be caught before you run anything. Adding lang="ts" to a component turns all of that on.

This lesson shows how to type the main building blocks of a component. A reminder about our runner: the in-page examples run plain JavaScript in the browser and cannot type-check, so every TypeScript snippet here is read-only. The runnable examples instead show what the types become at runtime, which is the part people most often misunderstand. If TypeScript itself is new to you, start with the TypeScript tutorial.

Setting up

The quickest start is npm create vue@latest and answering "yes" to TypeScript (see Ways to Use Vue). In an SFC you opt in per block:

VUE
<script setup lang="ts">
import { ref } from 'vue'

const count = ref(0) // inferred: Ref<number>
</script>

Two tools work together, and it helps to know what each does:

  • The editor extension ("Vue - Official", also called Volar) gives you completion, hover types and red squiggles for .vue files as you type.
  • vue-tsc is the command-line type checker for .vue files. Plain tsc cannot read them.

Vite, which builds most Vue apps, only strips the types (it transpiles each file and does not check anything). A build with type errors can still succeed unless you run vue-tsc yourself.

flowchart LR
  A["You type code<br/>in a .vue file"] --> B["Editor extension<br/>(live feedback)"]
  A --> C["vue-tsc<br/>(CI and build script)"]
  A --> D["Vite<br/>strips types, no checking"]
  D --> E["Browser<br/>runs plain JavaScript"]

Types exist in your editor and in vue-tsc. The browser never sees them.

A typical package.json wires the checker into the build so errors cannot ship:

JSON
{
  "scripts": {
    "dev": "vite",
    "build": "vue-tsc --noEmit && vite build",
    "type-check": "vue-tsc --noEmit"
  }
}

(The project that create-vue generates uses vue-tsc --build with several tsconfig files; the idea is the same.)

Typed props

With <script setup>, the simplest way to declare props in TypeScript is a type argument to defineProps:

VUE
<script setup lang="ts">
interface Props {
  title: string
  count?: number
  size?: 'sm' | 'md' | 'lg'
  featured?: boolean
}

const props = defineProps<Props>()
</script>

A question mark makes a prop optional; without it, the prop is required, and using the component without it is a type error in the parent's template. Literal unions such as 'sm' | 'md' | 'lg' give you autocomplete and reject size="huge".

Defaults

For defaults, use withDefaults, or (Vue 3.5 and later) give the destructured prop a default value:

TypeScript
// all Vue 3.3+
const props = withDefaults(defineProps<Props>(), {
  size: 'md',
  count: 0,
})

// Vue 3.5+: reactive props destructure, defaults are plain JavaScript defaults
const { size = 'md', count = 0 } = defineProps<Props>()

In the second form the compiler rewrites size to props.size, so the values stay reactive. Do not worry about the transformation; just remember that reading them inside watch needs a getter (() => size).

What the type becomes

Vue's props system needs a runtime description, since types are erased. The compiler reads your type and generates that description. The component above compiles to roughly:

JavaScript
props: {
  title: { type: String, required: true },
  count: { type: Number, required: false },
  size: { type: String, required: false },
  featured: { type: Boolean, required: false },
}

That is why the type must be something the compiler can resolve while compiling the file. Imported interfaces and many common utility types work in current Vue, but very elaborate conditional types may not. If the compiler complains, move to the runtime declaration with PropType:

TypeScript
import type { PropType } from 'vue'

defineProps({
  user: { type: Object as PropType<User>, required: true },
})

The next example is the runtime form of the component above. Notice how Boolean props behave: an absent boolean prop is false, and a bare attribute means true.

The runtime form of typed props

The poster has no count, so that part is hidden; the pin shows (0 in stock) because 0 is a valid number, not "missing".

Types are erased at runtime

The most important TypeScript fact in Vue is also the one beginners forget: the browser receives plain JavaScript. A prop typed number is only checked by vue-tsc and your editor. In a production build, a string passed to a number prop is not rejected. (The development build prints a warning, but production builds skip that check.)

Wrong type, no error at runtime

The first line shows 6 and 6. The second passes a string because start="5" without a colon is a string attribute. "5" + 1 is "51", and nothing stops it at runtime. With TypeScript, vue-tsc flags the second usage, because the prop is declared number. The lesson: types catch these mistakes at build time if you actually run the checker, and they do not replace validation of data that comes from outside your code (API responses, URL parameters, form fields).

Typed emits

Declare the payload of every event with a type argument. Vue 3.3 added a compact tuple syntax:

VUE
<script setup lang="ts">
const emit = defineEmits<{
  change: [id: number]
  update: [value: string, silent?: boolean]
  close: []
}>()

emit('change', 42)      // ok
emit('change', 'x')     // error: string is not a number
emit('chnage', 42)      // error: unknown event
</script>

The parent's handler is typed too: in @change="onChange", onChange receives a number. Learn the runtime side in Events and emits. For two-way bindings, defineModel accepts a type: const model = defineModel<string>(), and defineModel<number>({ required: true }) makes it required (see v-model on Components).

Typed refs, reactive and computed

Most of the time you write nothing: TypeScript infers the type from the initial value. Add a type argument when the initial value does not say enough:

TypeScript
import { ref, reactive, computed } from 'vue'

interface User { id: number; name: string }

const count = ref(0)                    // Ref<number>
const user = ref<User | null>(null)     // starts empty, later a User
const ids = ref<number[]>([])           // an empty array needs help

const form = reactive<{ name: string; age: number | null }>({ name: '', age: null })

const label = computed(() => `${form.name} (${form.age ?? '?'})`) // ComputedRef<string>
const doubled = computed<number>(() => count.value * 2)

Remember .value in script and automatic unwrapping in templates (Reactive State with ref). TypeScript will remind you: count + 1 on a Ref<number> is an error.

DOM events and template refs

Event handlers receive the real DOM event type, and event.target is typed as EventTarget | null, so you cast when you need the element:

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

Template refs need the element type and null for the time before mounting (Template Refs and Exposing Methods):

TypeScript
import { ref, onMounted, useTemplateRef } from 'vue'

const input = ref<HTMLInputElement | null>(null)

// Vue 3.5+: the ref name in the template is the key; tooling infers the element type
const box = useTemplateRef<HTMLDivElement>('box')

onMounted(() => input.value?.focus())

For a ref to a component, use InstanceType<typeof MyComponent>. Typed injection keys keep Provide and Inject honest:

TypeScript
import type { InjectionKey } from 'vue'

export const themeKey: InjectionKey<'light' | 'dark'> = Symbol('theme')
// provide(themeKey, 'dark')   and   const theme = inject(themeKey)  // type: 'light' | 'dark' | undefined

Generic components

Sometimes a component works for any item type: a list, a select, a table. Declare a type parameter on the script tag with the generic attribute:

VUE
<script setup lang="ts" generic="T extends { id: number }">
defineProps<{ items: T[]; selected?: T }>()
defineEmits<{ pick: [item: T] }>()
defineSlots<{ default(props: { item: T; index: number }): any }>()
</script>

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

Using it with users makes the slot's item a User; using it with products makes it a Product, with no casts. The runnable twin below is the same component without types. It behaves identically, since generics only exist for the checker.

A list component that works for any items

Click an entry and the line below updates. One component serves two item shapes; in TypeScript the generic T makes each use fully typed.

Practical advice

  • Let inference work. Annotate props, emits and the empty initial values; skip annotations on everything TypeScript already knows.
  • Avoid any and non-null assertions (!). Use ref<User | null> and check for null; the compiler then guards you in the template as well.
  • Run vue-tsc in CI. Otherwise the types are decoration.
  • Validate external data. Types describe what you expect. For API responses use a runtime validator, and keep the type derived from it.
  • Keep shared types in plain .ts files (types.ts) and import them with import type.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a Vite build succeed even when your .vue files contain type errors?

    Vite transpiles each file quickly without type information. To fail builds on type errors, run vue-tsc (for example in the build script and in CI).
  2. 2. What does defineProps<{ title: string; count?: number }>() produce at runtime?

    The compiler reads the type and generates the runtime props object. The development build can warn about mismatches, but production does not throw.
  3. 3. How do you type a ref that starts empty and later holds a User?

    The type argument states the full range of values: null before loading, a User afterward. ref<User>() with no argument would be Ref<User | undefined>.
  4. 4. What does the generic attribute on <script setup> do?

    generic="T extends ..." lets props, emits and slots mention T, so a list or select component keeps precise types for whatever items you give it. It has no runtime effect.

Summary

  • Add lang="ts" to <script setup> and install the Vue editor extension; use vue-tsc to check .vue files from the command line.
  • Vite strips types without checking, so put vue-tsc --noEmit in your build or CI.
  • defineProps<Props>() and defineEmits<{ name: [payload] }>() declare typed contracts; the compiler turns them into runtime declarations.
  • withDefaults (or reactive props destructure in Vue 3.5+) provides defaults.
  • Annotate empty refs (ref<User | null>(null)), template refs (HTMLInputElement | null) and injection keys (InjectionKey<T>).
  • generic="T" makes reusable list-style components fully typed.
  • Types are erased in the browser: they do not validate data that comes from outside your code.

Next: Code Quality and Style