In the previous lesson you extracted Colmena Bookings' filter, availability and request logic into composables, and at the end some questions were left unanswered in the code itself: what shape do the rooms that useRoomFilters receives have, what exactly does freeSlots contain, what type is data in useRequest? In JavaScript, those answers live in comments, in the team's memory and in the tests; if someone writes room.price instead of room.hourlyPrice, nothing warns them until the card shows "€NaN". TypeScript adds a static type system to JavaScript that the editor and the compiler check before anything runs, and Vue 3 is written in TypeScript and designed to take advantage of it. In this lesson you will set up TypeScript in a Vue project with Vite, migrate Colmena incrementally (file by file, without halting development), define the domain types and learn how to type every piece of Vue: props, events, v-model, refs, provide/inject, Pinia stores, the router, a plugin's global properties, generic components and composables.
A decision for the rest of the course. This lesson migrates Colmena to TypeScript, but the following lessons (from 09-03 onwards) will keep showing the code in JavaScript, so as not to duplicate every listing and so that the course remains useful to anyone not using TypeScript. Everything you see afterwards applies just the same with
<script setup lang="ts">: you only need to add the types following the guidelines in this lesson.
Contents
- Why TypeScript in Vue
- Setting it up in a Vite project
- An incremental migration strategy
- The domain types
- Typing
ref,reactiveandcomputed - Props with
definePropsand their default values - Events with
defineEmitsand slots withdefineSlots defineModel<T>()- Template refs with
useTemplateRef provideandinjectwithInjectionKey- Pinia stores
- The router:
RouteRecordRawandRouteMeta - Global properties: typing
$format - Generic components
- Typing Colmena's composables
- Typical type errors in templates
- Try it
- Why TypeScript in Vue
TypeScript is a superset of JavaScript: all valid JavaScript is valid TypeScript, and what it adds are type annotations that disappear on compilation. Its value lies in what it checks:
| Without TypeScript | With TypeScript |
|---|---|
room.price returns undefined at runtime |
The editor underlines price: "Property 'price' does not exist on type 'Room'" |
You pass :room="room.id" to RoomCard and it fails inside |
The error appears in the parent's template |
You rename myBookings in the store and search by hand for where it is used |
The compiler lists every broken use; the editor renames it across all files |
| Autocompletion guesses | Autocompletion knows the properties of every object, store and route |
| The shape of the data lives in comments | The shape of the data is code, and it does not go out of date |
And its costs, which are worth knowing:
| Cost | How it is mitigated |
|---|---|
One more tool (vue-tsc) and some configuration |
create-vue generates it; here we add it by hand once |
| A learning curve (generics, unions, narrowing) | Start with the simple things: typing data and props covers most of the benefit |
| More text in the code | Inference means most variables need no annotation |
| Third-party library types are sometimes imperfect | The main ones in the ecosystem (Vue, Vue Router, Pinia, Vue I18n, VueUse) are written in TypeScript |
Vue offers first-class integration: <script setup lang="ts"> with macros that understand types (defineProps<...>()), the editor's Vue (Official) extension, which also checks templates, and vue-tsc, which does the same from the command line.
- Setting it up in a Vite project
If you are starting a new project, npm create vue@latest asks whether you want TypeScript and generates everything in this section. Colmena was created without it in 01-02, so we will add it by hand, which also lets you understand each piece.
2.1 Dependencies
| Package | What for |
|---|---|
typescript |
The compiler and the type service |
vue-tsc |
Wraps tsc so that it understands .vue files, templates included |
@vue/tsconfig |
A base configuration recommended by the Vue team, to be extended |
Notice what is not needed: Vite already knows how to compile TypeScript. What it does not do is check the types: when compiling, it simply strips the annotations, very quickly, without analysing anything. If there is a type error, npm run dev and npm run build work just the same. Checking is the job of vue-tsc and the editor.
2.2 tsconfig.json and tsconfig.app.json
Create tsconfig.json in the root. It configures nothing by itself: it points to the repository's TypeScript projects:
And tsconfig.app.json, the configuration for the application's code:
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
"exclude": ["src/**/__tests__/*"],
"compilerOptions": {
"allowJs": true,
"checkJs": false,
"noUncheckedIndexedAccess": true,
"paths": {
"@/*": ["./src/*"]
},
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo"
}
}Line by line:
extends: inherits@vue/tsconfig's configuration for code that runs in the browser (tsconfig.dom.json): strict mode (strict), Vite-style module resolution (bundler),noEmit(TypeScript only checks; Vite is the one that compiles), JSX for Vue andverbatimModuleSyntax, which forces types to be imported withimport type(section 4) so that each file can be compiled separately.include: the code insrc/, including the.vuefiles, andenv.d.ts(section 2.3).exclude: the tests are left out for now; they will remain in JavaScript (section 3).allowJs: true: the key to the incremental migration..tsfiles can import.jsfiles and TypeScript understands them.checkJs: falsemeans the.jsfiles are not checked: each file starts being checked when you migrate it.noUncheckedIndexedAccess: makeslist[0]orobject[key]have the typeT | undefined, because there may be nothing in that position. It is stricter than the default mode andcreate-vueenables it too; it catches real bugs, as you will see in section 16.paths: the@/alias fromvite.config.js. Vite resolves the alias when compiling, and TypeScript needs to know about it to find the files.tsBuildInfoFile:vue-tsc --buildstores information for the next incremental check; this way it does not clutter the root.
A project created with
create-vueand TypeScript also includestsconfig.node.json(forvite.config.tsand other configuration files, which run in Node) andtsconfig.vitest.json(for the tests). In Colmena we are leaving the configuration files and the tests in JavaScript, so for the time being the application project is enough.
2.3 env.d.ts
In the root, env.d.ts adds the types that Vite injects into the code, such as import.meta.env:
/// <reference types="vite/client" />
// Our own environment variables (those in .env.e2e, 08-04)
interface ImportMetaEnv {
readonly VITE_STABLE_SIMULATION?: string
}vite/clientdeclaresimport.meta.env.DEV,import.meta.env.BASE_URL, image and CSS imports...ImportMetaEnvis extended with our variables. With this,import.meta.env.VITE_STABLE_SIMULATIONis autocompleted and a typo in its name is caught.
2.4 The checking script
In package.json:
npm run type-check checks the whole project, templates included, and exits with an error if it finds any. Use it before every commit and in continuous integration (10-03). You can chain it to build ("build": "vue-tsc --build && vite build") so that a version with type errors cannot be built; create-vue does this with npm-run-all2, running the check and the build in parallel.
2.5 The editor
The Vue (Official) extension you installed in 01-02 uses the project's TypeScript to check .vue files as you type: it underlines errors in the script and in the template, shows the type of each expression when you hover over it and autocompletes props and events. You do not need to install anything else. If the editor shows errors that vue-tsc does not report (or vice versa), restart the Vue server from the command palette: it tends to happen after changing the tsconfig files.
- An incremental migration strategy
Migrating a whole application in one go is risky for the same reason that migrating from Vuex to Pinia was (05-07): while it lasts, nothing works. With allowJs, the application works at all times: each file is migrated when its turn comes, and those still in JavaScript coexist with the new ones.
The order matters. It is best to start with whatever depends on nothing and everything uses, because each migrated file gives types to the files that import it:
flowchart LR
T["1. Domain types<br/>src/types/domain.ts"] --> U["2. Utilities<br/>dates.ts"]
U --> A["3. API<br/>src/api/*.ts"]
A --> S["4. Stores<br/>src/stores/*.ts"]
S --> C["5. Composables<br/>src/composables/*.ts"]
C --> H["6. Leaf components<br/>StatusBadge, BaseButton,<br/>TextField, RoomCard"]
H --> V["7. Views"]
V --> R["8. router, plugins, main.ts"]
For each file:
- Rename it from
.jsto.ts(or, in a.vuefile, change<script setup>to<script setup lang="ts">). - Run
npm run type-checkand fix whatever comes up: almost always annotations on function parameters and onrefs that start out empty. - Run
npm test: the tests, which are still in JavaScript, check that the behaviour has not changed.
A practical detail: existing imports, such as import { toMinutes } from '@/utils/dates.js', keep working after renaming the file to dates.ts: both TypeScript (with bundler resolution) and Vite resolve the .js extension to the .ts file. You do not need to touch the files that import it. In new code written in TypeScript, the usual thing is to import without an extension ('@/utils/dates').
In older projects you will see a
shims-vue.d.tsfile withdeclare module '*.vue'. It was necessary when the editor did not understand.vuefiles; with Vue (Official) andvue-tscit is superfluous, and it also hides the components' real types. If you inherit one, delete it.
- The domain types
The first file is not migrated: it is created. src/types/domain.ts describes Colmena's data model, which until now only existed in the course documentation:
// src/types/domain.ts
// Colmena Bookings' data model
export type Equipment = 'projector' | 'whiteboard' | 'screen' | 'videoconference' | 'microphone'
export interface Room {
id: string
name: string
floor: 1 | 2 | 3
capacity: number
hourlyPrice: number
equipment: Equipment[]
available: boolean
}
export type BookingStatus = 'confirmed' | 'pending' | 'cancelled'
export interface Booking {
id: string
roomId: Room['id']
date: string // 'YYYY-MM-DD'
startTime: string // 'HH:MM'
endTime: string // 'HH:MM'
member: string
attendees: number
status: BookingStatus
extraEquipment: string[]
notes: string
}
// What the form submits: the server assigns the id
export type BookingData = Omit<Booking, 'id'> & { id?: string }
export type Plan = 'flexible' | 'fixed' | 'business'
export type Role = 'member' | 'manager'
export interface Session {
name: string
email: string
plan: Plan
role: Role
}
// Errors from the simulated API (errorWithStatus, 07-03)
export interface ApiError extends Error {
status?: number
code?: string | null
data?: Record<string, unknown>
}The tools we have used:
| Construct | Example | Meaning |
|---|---|---|
interface |
interface Room { ... } |
The shape of an object: which properties it has and of what type |
| Union of literals | 'confirmed' | 'pending' | 'cancelled' |
Only those exact values; 'canceled' is an error |
| Type of a property | Room['id'] |
"The same type as a room's id": if it changes, it changes everywhere |
Omit<T, K> |
Omit<Booking, 'id'> |
Booking without the id property |
| Intersection | A & { id?: string } |
The properties of both; ? makes the property optional |
extends |
interface ApiError extends Error |
Everything in Error, plus the new bits |
floor: 1 | 2 | 3 is more precise than number: if someone tries to create a room on floor 4, the error appears as they type it. But be careful not to overdo it: date is a string and not a more elaborate type, because types cannot usefully validate a date's format; that is the job of runtime validation.
These types are for the compiler only: they generate no code. They are imported with import type, which makes it clear (to you and to Vite) that the import disappears on compilation:
- Typing
ref, reactive and computed
ref, reactive and computedMost of the time, TypeScript infers the type and there is nothing to write:
const attendees = ref(0) // Ref<number>
const search = ref('') // Ref<string>
const full = computed(() => attendees.value >= 8) // ComputedRef<boolean>You need to annotate when the initial value is not enough to deduce the type:
import { ref, reactive, computed } from 'vue'
import type { Room, Booking } from '@/types/domain'
// An empty array: without an annotation, it would be never[] and would not accept rooms
const rooms = ref<Room[]>([])
// A value that starts as null and will later have another type
const loadedAt = ref<number | null>(null)
// A union of literals: without an annotation, it would be string
const catalogView = ref<'grid' | 'table' | 'map'>('grid')
// reactive: annotate the variable (the generic reactive<T>() is not recommended)
const form: Pick<Booking, 'roomId' | 'date' | 'attendees'> = reactive({
roomId: 'panal',
date: '',
attendees: 1
})
// computed: the generic declares the return type and checks the function
const availableRooms = computed<Room[]>(() => rooms.value.filter((r) => r.available))With src/utils/dates.js renamed to dates.ts, its functions only need their parameters annotated (the return type is inferred, although annotating it on exported functions documents the contract):
// src/utils/dates.ts (excerpt)
export function toMinutes(time: string): number {
const [hours = 0, minutes = 0] = time.split(':').map(Number)
return hours * 60 + minutes
}
export function durationHours(startTime: string, endTime: string): number {
return (toMinutes(endTime) - toMinutes(startTime)) / 60
}Notice [hours = 0, minutes = 0]: with noUncheckedIndexedAccess, destructuring an array gives number | undefined, because '10'.split(':') has only one element. The default values solve it and, incidentally, make the function more robust.
- Props with
defineProps and their default values
defineProps and their default values6.1 Type-based declaration
In JavaScript you declare props with a runtime options object ({ room: { type: Object, required: true } }). With TypeScript, defineProps accepts a type as a generic, and Vue's compiler generates the runtime options from it. This is what RoomCard.vue looks like:
<script setup lang="ts">
import type { Room } from '@/types/domain'
const { room, selected = false } = defineProps<{
room: Room
selected?: boolean
}>()
</script>room: Roomis required;selected?: booleanis optional.- The type is far more precise than
type: Object: inside the component,room.hourlyPriceis anumberandroom.equipmentan array of five possible values, and in the parent,:room="room.id"is an error. - Imported types can be used (
Roomcomes from another file). What the compiler does not accept are complex conditional types insidedefineProps, because it has to translate them into runtime options.
6.2 Default values: destructuring versus withDefaults
There are two ways of giving default values with type-based props:
// 1. Reactive destructuring (Vue 3.5+): the one we have used in the course since 03-02
const { selected = false, level = 2 } = defineProps<{
selected?: boolean
level?: 1 | 2 | 3
}>()
// 2. withDefaults: the pre-3.5 way, very common in existing code
const props = withDefaults(
defineProps<{
selected?: boolean
equipmentOptions?: string[]
}>(),
{
selected: false,
equipmentOptions: () => [] // objects and arrays, with a factory function
}
)| Reactive destructuring | withDefaults |
|
|---|---|---|
| Vue version | 3.5+ | 3.3+ (earlier, with warnings) |
| Access | selected |
props.selected |
| Default arrays and objects | equipmentOptions = [] without a factory: the compiler handles it |
Needs a factory () => [] |
Passing a prop to a composable or to watch |
With a getter: () => selected (09-01) |
() => props.selected or toRef(props, 'selected') |
In Colmena we are sticking with destructuring. Recognising withDefaults will serve you in any project that predates Vue 3.5.
- Events with
defineEmits and slots with defineSlots
defineEmits and slots with defineSlotsdefineEmits also accepts a type. The recommended syntax describes each event with a named tuple of its arguments:
// RoomCard.vue
const emit = defineEmits<{
select: [id: Room['id']]
book: [payload: { roomId: Room['id']; attendees: number }]
}>()
emit('select', room.id) // correct
emit('book', { roomId: room.id, attendees: attendees.value }) // correct
emit('book', room.id) // error: the object is missing
emit('booking', room.id) // error: the event does not existThe tuple's names (id, payload) do not affect the type, but they appear in autocompletion and document what each argument is. In the parent, the handler is typed: in @book="prepareBooking", if prepareBooking expects another shape, the error appears in the template.
Scoped slots can also be typed, with defineSlots. In RoomCard, the #actions slot receives the room, the attendees and whether it is full (03-04):
// RoomCard.vue
defineSlots<{
actions?(props: { room: Room; attendees: number; full: boolean }): unknown
}>()With this, in <template #actions="{ full }">, full is a boolean and writing { isFul } is an error. The ? indicates that the slot is optional.
defineModel<T>()
defineModel<T>()defineModel (03-03) receives the model's type as a generic. RoomFilters has five:
// RoomFilters.vue
import type { SortOrder } from '@/composables/useRoomFilters'
const floor = defineModel<number | null>('floor', { default: null })
const minCapacity = defineModel<number>('minCapacity', { default: 1 })
const equipment = defineModel<string>('equipment', { default: '' })
const sort = defineModel<SortOrder>('sort', { default: 'none' })
const search = defineModel<string>('search', { default: '' })
const { equipmentOptions = [] } = defineProps<{ equipmentOptions?: string[] }>()floor.value = 4 is still valid for TypeScript (it is a number), but sort.value = 'most-expensive' is not. And in the parent, v-model:sort="floorFilter" is an error, because floorFilter is not a SortOrder.
TextField also has a custom modifier, .uppercase. The second generic declares the accepted modifiers:
// TextField.vue
const [model, modifiers] = defineModel<string | number, 'uppercase'>({
set(value) {
return modifiers.uppercase && typeof value === 'string' ? value.toUpperCase() : value
}
})modifiers.uppercase is a boolean | undefined, and typeof value === 'string' narrows the type of value: inside that branch, TypeScript knows it is a string and allows toUpperCase(). Without the check, the compiler would warn that a number does not have that method, and it would be right: with v-model.number, the value can be a number.
- Template refs with
useTemplateRef
useTemplateRefuseTemplateRef (03-05) cannot know by itself which element in the template has that name, so you tell it with the generic:
// TextField.vue
import { useId, useTemplateRef } from 'vue'
defineOptions({ inheritAttrs: false })
const { label, error = '' } = defineProps<{
label: string
error?: string
}>()
const id = useId()
const inputElement = useTemplateRef<HTMLInputElement>('input')
function focusField() {
inputElement.value?.focus() // inputElement.value is HTMLInputElement | null
}
defineExpose({ focusField })HTMLInputElement | null: before mounting (and after unmounting) there is no element, so the type includesnulland TypeScript forces you to check it (?.).- For a child component, the type is the component's instance:
useTemplateRef<InstanceType<typeof BookingForm>>('booking-form')gives typed access to what it exposes withdefineExpose(reset,hasChanges).
provide and inject with InjectionKey
provide and inject with InjectionKeyWith inject(CONFIG_KEY), TypeScript cannot know what type the provided value has: the key is just any symbol. InjectionKey<T> is a symbol that carries the type with it. Rename src/keys.js to keys.ts:
// src/keys.ts
import type { InjectionKey } from 'vue'
export interface CentreConfig {
centreName: string
openingHour: number
closingHour: number
}
export const CONFIG_KEY: InjectionKey<CentreConfig> = Symbol('config')Now both ends are checked:
// main.ts: an object without closingHour would be an error
app.provide(CONFIG_KEY, { centreName: 'Coworking Colmena', openingHour: 8, closingHour: 20 })
// In a component
const config = inject(CONFIG_KEY)
// CentreConfig | undefined: perhaps no ancestor has provided it
const { openingHour, closingHour } = inject(CONFIG_KEY, {
centreName: 'Coworking Colmena',
openingHour: 8,
closingHour: 20
}) // with a default value: CentreConfig, without undefinedThe | undefined in the first case is honest: inject may find nothing. With a default value (which must have the type's complete shape), it disappears. formatPlugin (07-02) follows the same pattern with its FORMAT_KEY.
- Pinia stores
Setup stores almost type themselves: the store's type is that of the object the function returns, and each ref, computed and function keeps its type. You only need to annotate the refs that start out empty and the actions' parameters:
// src/stores/rooms.ts (excerpt)
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { api } from '@/api'
import type { Room } from '@/types/domain'
export const useRoomsStore = defineStore('rooms', () => {
const rooms = ref<Room[]>([])
const loadedAt = ref<number | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const catalogView = ref<'grid' | 'table' | 'map'>('grid')
const availableRooms = computed(() => rooms.value.filter((room) => room.available))
const roomById = computed(() => (id: string) => rooms.value.find((room) => room.id === id))
function loadRooms({ force = false }: { force?: boolean } = {}): Promise<void> {
// ... unchanged
}
// ... $reset and return, unchanged
})In the components, everything arrives typed without doing anything: roomsStore.roomById('panal') is Room | undefined (and TypeScript will force you to handle the undefined), and storeToRefs(roomsStore).catalogView is a Ref<'grid' | 'table' | 'map'>, so currentView.value = 'mosaic' is an error.
One detail remains: the persistence option that our persistence plugin reads (05-07) does not exist as far as Pinia is concerned, and defineStore('bookings', () => {...}, { persistence: ... }) would produce an error. It is declared by augmenting Pinia's options interface, in src/stores/plugins/persistence.d.ts:
// src/stores/plugins/persistence.d.ts
import 'pinia'
declare module 'pinia' {
export interface DefineStoreOptionsBase<S, Store> {
persistence?: {
storage: Storage
key: string
fields: string[]
}
}
}This is TypeScript's module augmentation: declare module 'pinia' reopens the library's declarations and adds a property to an existing interface. You will see it three times in this lesson, because it is the standard mechanism through which Vue libraries let you add types to them. The import 'pinia' at the start is necessary: it turns the file into a module and makes the declaration augment the module instead of replacing it.
- The router:
RouteRecordRaw and RouteMeta
RouteRecordRaw and RouteMetaWhen you rename src/router/index.js to index.ts, the routes are annotated with RouteRecordRaw, and the helper functions with Vue Router's types:
// src/router/index.ts (excerpt)
import { createRouter, createWebHistory, type RouteRecordRaw, type RouteLocationNormalized } from 'vue-router'
function bookingProps(route: RouteLocationNormalized) {
const attendees = Number(route.query.attendees)
return {
roomId: route.params.roomId,
attendees: Number.isInteger(attendees) && attendees > 0 ? attendees : 1
}
}
const routes: RouteRecordRaw[] = [
{ path: '/', name: 'home', component: HomeView, meta: { title: 'Home' } },
// ... the rest, unchanged
]And meta? By default, route.meta is an object holding anything (Record<string | number | symbol, unknown>), so to.meta.title is unknown and to.meta.role === 'manager' does not protect you from typos. It is fixed by augmenting the RouteMeta interface, in src/types/router.d.ts:
// src/types/router.d.ts
import 'vue-router'
import type { Role } from './domain'
declare module 'vue-router' {
interface RouteMeta {
title?: string
requiresSession?: boolean
role?: Role
transition?: string // we will use it in 09-04
}
}Now to.meta.title is string | undefined in the guards, meta: { role: 'admin' } on a route is an error, and autocompletion knows the meta fields. We have already declared transition, which we will add to the routes in Transitions and Animations.
- Global properties: typing
$format
$formatIn 07-02, formatPlugin added $format to app.config.globalProperties so that it could be used in templates ({{ $format.price(room.hourlyPrice) }}), and we promised to type it here. Without types, vue-tsc says that $format does not exist on the component. The solution is to augment ComponentCustomProperties, the Vue interface that describes the properties available in every template:
// src/plugins/format.ts (excerpt)
import type { App, InjectionKey, MaybeRefOrGetter } from 'vue'
export interface Format {
price(amount: number): string
date(value: string | Date, style?: 'long' | 'short' | 'numeric'): string
time(value: Date, options?: { seconds?: boolean }): string
duration(hours: number): string
readonly locale: string
}
export interface FormatOptions {
locale?: MaybeRefOrGetter<string>
currency?: string
}
export const FORMAT_KEY: InjectionKey<Format> = Symbol('format')
// ... createFormat(options: FormatOptions): Format, formatPlugin and useFormat(): Format
declare module 'vue' {
interface ComponentCustomProperties {
$format: Format
}
}- The
Formatinterface describes the service only once.createFormatdeclares that it returns aFormat, so doesuseFormat, and the injection key carries it in its type. declare module 'vue'augments Vue so that$formatexists in every template with that type.{{ $format.price('25') }}(a string) or{{ $format.hourlyPrice(25) }}are now errors.- The augmentation goes in the same file as the plugin: whoever installs the plugin gets the types. Because it is in a file with an
import, it is already a module and does not need theimport 'vue'of the.d.tsfiles.
Libraries' global properties are declared in exactly the same way: it is what Vue I18n does so that $t exists in your templates, and Vue Router for $route and $router.
- Generic components
Sometimes a component works with data of any type, but wants to preserve that type: a list that receives items and emits the chosen one should emit a Room if it received rooms, and a Booking if it received bookings. This is what TypeScript calls a generic, and <script setup> supports it with the generic attribute:
<!-- src/components/base/SelectableList.vue -->
<script setup lang="ts" generic="T extends { id: string }">
const { items, label } = defineProps<{
items: T[]
label: (item: T) => string
}>()
const selected = defineModel<T['id'] | null>({ default: null })
const emit = defineEmits<{
choose: [item: T]
}>()
defineSlots<{
default?(props: { item: T; selected: boolean }): unknown
}>()
function choose(item: T) {
selected.value = item.id
emit('choose', item)
}
</script>
<template>
<ul class="selectable-list" role="listbox">
<li
v-for="item in items"
:key="item.id"
role="option"
:aria-selected="item.id === selected"
tabindex="0"
@click="choose(item)"
@keydown.enter="choose(item)"
>
<slot :item="item" :selected="item.id === selected">
{{ label(item) }}
</slot>
</li>
</ul>
</template>generic="T extends { id: string }"declares the type parameterT, with a constraint: any type will do, as long as it has a stringid(we need it for thekeyand for the model).Tis used throughout the component: in the props, the model, the events and the slots.- In the parent,
Tis inferred from what is passed initems. You never have to write it:
<script setup lang="ts">
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import SelectableList from '@/components/base/SelectableList.vue'
import { useRoomsStore } from '@/stores/rooms'
import type { Room } from '@/types/domain'
const { rooms } = storeToRefs(useRoomsStore())
const roomId = ref<string | null>(null)
function openSpecSheet(room: Room) {
// room is a Room: room.hourlyPrice is autocompleted
}
</script>
<template>
<SelectableList
v-model="roomId"
:items="rooms"
:label="(room) => `${room.name} · ${room.capacity} people`"
@choose="openSpecSheet"
>
<template #default="{ item }">{{ item.name }} (floor {{ item.floor }})</template>
</SelectableList>
</template>With :items="rooms", T is Room: in the label function, room is typed without annotating it; in the slot, item.floor exists; and :label="(room) => room.capacity" would be an error, because it returns a number and a string was expected. The same component with :items="bookingsStore.myBookings" would have T = Booking. This is impossible to express with runtime props (type: Array): it is where TypeScript brings the biggest gain in base components.
- Typing Colmena's composables
The composables from 09-01 are ordinary functions, so they are typed as such. Their characteristic feature is the arguments that can be a value, a ref or a getter: Vue's MaybeRefOrGetter<T> type.
15.1 useRequest: a generic composable
useRequest does not know what data it loads: invoices, rooms, anything. It expresses this with two generics, P (the parameter) and T (the data):
// src/composables/useRequest.ts
import { ref, shallowRef, watch, toValue, onScopeDispose } from 'vue'
import type { MaybeRefOrGetter, Ref, ShallowRef } from 'vue'
export type Loader<P, T> = (param: P, options: { signal: AbortSignal }) => Promise<T>
export interface RequestState<T> {
data: ShallowRef<T | null>
loading: Ref<boolean>
error: ShallowRef<unknown>
reload: () => Promise<void>
}
export function useRequest<P, T>(loader: Loader<P, T>, source: MaybeRefOrGetter<P>): RequestState<T> {
const data = shallowRef<T | null>(null)
const loading = ref(false)
const error = shallowRef<unknown>(null)
let controller: AbortController | null = null
// reload, watch and onScopeDispose: identical to the 09-01 version
}In the view no types are written: TypeScript infers P and T from the loader. If fetchInvoices (migrated to TypeScript) returns Promise<Invoice[]>, then invoices is a ShallowRef<Invoice[] | null>, and invoices.value.filter(...) is an error until you handle the null (which is why we wrote invoices.value ?? []).
errorisunknown, notError: in JavaScript anything can be thrown (throw 'text'). TypeScript forces you to check it before using it;translateErrorcan receive theunknownand check internally whether it has acode.
15.2 useRoomFilters and useAvailability
// src/composables/useRoomFilters.ts (signature and types)
import type { MaybeRefOrGetter, WritableComputedRef } from 'vue'
import type { Room, Equipment } from '@/types/domain'
export type SortOrder = 'none' | 'price-asc' | 'price-desc'
interface UrlFilters {
floor: number | null
capacity: number
equipment: Equipment | ''
sort: SortOrder
q: string
}
export function useRoomFilters(rooms: MaybeRefOrGetter<Room[]>) {
// ...
function filterInUrl<K extends keyof UrlFilters>(key: K): WritableComputedRef<UrlFilters[K]> {
return computed({
get: () => urlFilters.value[key],
set: (value) => {
applyFilters({ [key]: value })
}
})
}
// ...
}filterInUrl is the most interesting example: K extends keyof UrlFilters means the key can only be one of the five, and the return type, UrlFilters[K], depends on which one. So filterInUrl('floor') returns a WritableComputedRef<number | null> and filterInUrl('sort') one of SortOrder, without writing five functions. That is why RoomFilters could declare defineModel<SortOrder>('sort') in section 8 and the view fits without conversions.
// src/composables/useAvailability.ts (signature and types)
import type { MaybeRefOrGetter } from 'vue'
import type { Booking } from '@/types/domain'
export interface TimeSlot {
startTime: string
endTime: string
}
export function overlap(a: TimeSlot, b: TimeSlot): boolean { /* ... */ }
export function useAvailability(
roomId: MaybeRefOrGetter<string | null | undefined>,
date: MaybeRefOrGetter<string>
) {
// ...
function conflictsWith(startTime: string, endTime: string): Booking | null { /* ... */ }
// ...
}overlap(a: TimeSlot, b: TimeSlot)also accepts bookings: aBookinghasstartTimeandendTime, and TypeScript compares shapes, not type names (structural typing). There is no need to declare thatBooking"is" aTimeSlot.- The return type is not annotated: TypeScript infers it from the
return, and whoever callsuseAvailabilityseesfreeSlots: ComputedRef<TimeSlot[]>on hovering. inject's default value must now have the complete shape ofCentreConfig, includingcentreName(section 10).
- Typical type errors in templates
vue-tsc checks template expressions just as it checks the script. These are the errors you will see most often when migrating Colmena, and how to fix them:
| Message (abridged) | Example | Cause and solution |
|---|---|---|
Object is possibly 'undefined' |
{{ rooms[0].name }} |
With noUncheckedIndexedAccess, rooms[0] may not exist. Use rooms[0]?.name or a v-if |
'room' is possibly 'null' |
{{ room.name }} in RoomDetailView |
room is Room | null. The v-else-if="room" that the template already has narrows the type inside its block: the error means the expression is outside it |
Property 'value' does not exist on type 'HTMLElement' |
@input="runSearch($event.target.value)" |
$event.target is a generic EventTarget. Use ($event.target as HTMLInputElement).value or, better, v-model |
Type 'number' is not assignable to type 'string' |
:label="(r) => r.capacity" |
The prop expects another type; the error points to the exact prop |
Property '$format' does not exist |
{{ $format.price(...) }} |
The ComponentCustomProperties augmentation is missing (section 13), or the file containing it is not in include |
Argument of type ... is not assignable on an @event |
@book="prepareBooking" |
The handler does not accept what the child emits. Check prepareBooking's signature |
| Errors in a component still in JS | <RoomCard :room="room" /> from a .vue without lang="ts" |
A component without lang="ts" has loosely typed props (the runtime ones). Once it is migrated, its uses are properly checked |
Two general tips:
- Prefer narrowing to asserting.
v-if="room",?.and??make TypeScript prove that the value exists.room!.nameoras Roomonly tell it "trust me", and if you are wrong, the error reappears at runtime. asin templates is allowed withlang="ts"and is acceptable for DOM events ($event.target as HTMLInputElement), where the type genuinely cannot be inferred.
- Try it
- Installation. Install the dependencies, create
tsconfig.json,tsconfig.app.jsonandenv.d.ts, and add the script.npm run type-checkfinishes without errors: withcheckJs: false, none of the existing code is checked yet. - An error caught. Create
src/types/domain.tsand migrateRoomCard.vuetolang="ts"with the props and events from section 7. InRoomList.vue(still in JavaScript), nothing changes. Now temporarily write{{ room.price }}in the card's template: the editor underlines it andnpm run type-checkfails, pointing to the line. Remove it. - Vite does not check types. With that same error, run
npm run dev: the application starts and shows the card (with an empty price). This is the difference between compiling and checking. - The router. Migrate the router and create
src/types/router.d.ts. On a route, writemeta: { role: 'admin' }: error. In a guard, hover overto.meta.title:string | undefined. $format. Migratesrc/plugins/format.jswith theComponentCustomPropertiesaugmentation. In the template of a component withlang="ts", type$format.and check the autocompletion withprice,date,time,durationandlocale.- Generics. Create
SelectableListand use it temporarily inHomeViewwith the rooms: hover overitemin the slot and you will seeRoom. Change:itemstobookingsStore.myBookings:item.namebecomes an error, because a booking has noname. - The tests still do their job. After each migrated file,
npm testandnpm run test:e2estay green: the JavaScript tests import the TypeScript modules without any changes.
Common Mistakes and Tips
- Believing that Vite checks types. It only strips them. Without
vue-tscin your workflow (before committing, in CI, in thebuild), type errors reach production. - Migrating everything in one go. With
allowJs, migrate file by file, starting with the types and the utilities, and with the application working after each step. - Using
anyto make the errors go away. It switches the compiler off exactly where it is most needed. If you do not know the type, useunknownand narrow it with checks. - Overusing
asand!. Asserting a type does not make it true. Preferv-if,?.,??and checks withtypeoforin. - Duplicating the domain types in every component (
{ id: string; name: string; ... }). Define them once insrc/types/domain.tsand reuse them, also viaRoom['id'],PickorOmit. - Forgetting the
importin module augmentation files (import 'pinia',import 'vue-router'). Without it, the declaration replaces the module instead of augmenting it, and strange errors appear throughout the application. - Mixing type-based and options-based declaration in the same
defineProps. It is one or the other. - Passing a destructured prop to
watchor to a composable without a getter. With TypeScript it is still the same mistake as in 09-01, even if the types match. - Tip: hover over it. The quickest way to understand a type error is to see what type TypeScript thinks each part of the expression has.
- Tip: once you have finished the migration, consider enabling
checkJs: truefor the files that remain in JavaScript (the tests, for example): TypeScript will check them using inference and JSDoc comments.
Exercises
Exercise 1. Migrate src/components/StatusBadge.vue to TypeScript. Its status prop accepts six values: the three statuses of a room ('available', 'full', 'unavailable') and the three of a booking. Define a RoomStatus type in domain.ts and use a union with BookingStatus for the prop, so that the runtime validator you wrote in module 3 is no longer needed. Is there any case in which it would be worth keeping it?
Exercise 2. Migrate src/api/rooms.js to TypeScript. fetchRooms and fetchRoom must declare that they return Promise<Room[]> and Promise<Room>, and errorWithStatus (in simulation.js, which you will also migrate) must return an ApiError. Then check what type roomsStore.rooms has and what happens if in loadRooms you mistakenly assign rooms.value = await api.rooms.fetchRoom('panal').
Exercise 3. Write the TypeScript version of translateError (in src/i18n.ts), which receives an unknown, so that it works with anything that has been thrown. Hint: write a type guard function isApiError(value: unknown): value is ApiError.
Solutions
Solution 1.
<!-- src/components/StatusBadge.vue -->
<script setup lang="ts">
import type { RoomStatus, BookingStatus } from '@/types/domain'
const { status } = defineProps<{
status: RoomStatus | BookingStatus
}>()
// ... labels and classes, unchanged
</script>With TypeScript, <StatusBadge status="canceled" /> is an error as you type it, in the editor and in vue-tsc, so the validator is redundant within Colmena. It is only worth keeping (combining defineProps with runtime options instead of a type) if the component were published as a library for JavaScript projects, or if the value came from untyped external data (an API), where TypeScript cannot guarantee anything at runtime.
Solution 2.
// src/api/simulation.ts (excerpt)
import type { ApiError } from '@/types/domain'
export function errorWithStatus(
message: string,
status: number,
code: string | null = null,
data: Record<string, unknown> = {}
): ApiError {
const error: ApiError = new Error(message)
error.status = status
error.code = code
error.data = data
return error
}// src/api/rooms.ts
import { rooms } from '@/data/rooms.js'
import { wait, randomDelay, failSometimes, errorWithStatus } from './simulation'
import type { Room } from '@/types/domain'
export async function fetchRooms(
{ floor = null }: { floor?: number | null } = {},
{ signal }: { signal?: AbortSignal } = {}
): Promise<Room[]> {
await wait(randomDelay(), signal)
failSometimes()
const result = floor === null ? rooms : rooms.filter((room) => room.floor === floor)
return structuredClone(result) as Room[]
}
export async function fetchRoom(id: string, { signal }: { signal?: AbortSignal } = {}): Promise<Room> {
// ... the same, throwing errorWithStatus(..., 404, 'roomNotFound', { roomId: id })
}The as Room[] is necessary while src/data/rooms.js stays in JavaScript: TypeScript infers floor: number and equipment: string[], which are wider than those of Room. If you also migrate rooms.ts and annotate export const rooms: Room[] = [...], the assertion becomes unnecessary (and that is preferable). In the store, roomsStore.rooms is Room[], and assigning the result of fetchRoom (a Room, not an array) gives the error "Type 'Room' is missing the following properties from type 'Room[]': length, pop, push..." on that very line.
Solution 3.
// src/i18n.ts (excerpt)
import type { ApiError } from '@/types/domain'
function isApiError(value: unknown): value is ApiError {
return value instanceof Error && 'code' in value
}
export function translateError(error: unknown): string {
if (!error) return ''
const { t, te } = i18n.global
if (isApiError(error) && error.code) {
const key = `errors.api.${error.code}`
if (te(key)) return t(key, error.data ?? {})
}
if (import.meta.env.DEV) console.warn('[i18n] Untranslated error:', error)
return t('errors.api.unknown')
}A type guard (value is ApiError) is a function that returns a boolean and, in addition, tells TypeScript that, if it returns true, the value is of that type. Inside the if, error.code and error.data are available with their types. Because it receives unknown, translateError accepts without complaint both useRequest's error.value and the error from any catch.
Conclusion
TypeScript adds type checking to Vue, which the editor (with Vue (Official)) and vue-tsc apply to both the script and the templates, while Vite simply strips the annotations. You have set Colmena up with tsconfig.json, tsconfig.app.json (with allowJs to migrate file by file), env.d.ts and the type-check script; you have defined the data model in src/types/domain.ts (Room, Booking, BookingStatus, Session, Plan, Role); and you have seen how each piece is typed: ref and computed by inference or with generics, props with defineProps<...>() and reactive destructuring (or withDefaults in older code), events with named tuples, slots with defineSlots, defineModel<T>() with its modifiers, useTemplateRef<HTMLInputElement>, InjectionKey for provide/inject, setup stores that type themselves, RouteRecordRaw and the augmentation of RouteMeta, $format through ComponentCustomProperties, generic components such as SelectableList<T> and composables with MaybeRefOrGetter. Remember the decision made at the start: from here on the course shows JavaScript, and everything applies equally with lang="ts".
Until now, all of Colmena's interfaces have been described with templates, and Vue's compiler has turned them into code for us. But some components fit badly into a template: a title whose heading level depends on a prop, a table whose columns arrive as data, an icon that needs no state or lifecycle. For them, Vue lets you write directly what the compiler generates, as you will see in Render Functions and JSX.
Vue.js Course
Module 1: Introduction to Vue.js
- What Is Vue.js?
- Setting Up the Development Environment
- Creating Your First Vue Application
- Understanding the Vue Instance: Application, Components and Lifecycle
- Options API and Composition API: Two Ways to Write Components
Module 2: Vue.js Basics
- Template Syntax
- Reactivity: ref and reactive
- Data Binding
- Event Handling
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Forms with v-model
Module 3: Vue.js Components
- Introduction to Components
- Props and Custom Events
- v-model on Your Own Components
- Slots
- Template Refs and Fallthrough Attributes
- Dynamic and Async Components
- Component Communication
Module 4: Vue Router
- Introduction to Vue Router
- Setting Up Vue Router
- Dynamic Routes
- Nested Routes
- Programmatic Navigation and Query Parameters
- Navigation Guards
Module 5: State Management with Vuex and Pinia
- Introduction to Vuex
- State, Getters, Mutations and Actions
- Vuex Modules
- Using Vuex in Components
- Advanced Vuex Patterns
- Pinia: The Recommended State Management for Vue 3
- Migrating from Vuex to Pinia
Module 6: Vue.js Directives
Module 7: Vue.js Plugins
Module 8: Testing in Vue.js
- Unit Testing with Vue Test Utils and Vitest
- Mocking Dependencies
- Testing Composables and Stores
- End-to-End Testing with Cypress
Module 9: Advanced Vue.js Concepts
- The Vue 3 Composition API in Depth: Composables and Logic Reuse
- Vue with TypeScript
- Render Functions and JSX
- Transitions and Animations
- Teleport, Suspense and Error Handling
- Server-Side Rendering (SSR) with Nuxt
- Performance Optimization
