Vue with TypeScript
Vue 3 is written in TypeScript and has first-class TypeScript support. With types, your editor knows the shape of props, events, refs and stores, catches typos before you run the code, and autocompletes everything. This is a concept lesson: TypeScript in .vue files needs a build step, so the TS code is shown as plain code, and the playgrounds show the same components in JavaScript.
Setting up
Choose TypeScript when scaffolding:
npm create vue@latest my-ts-app -- --typescript> npx
> create-vue my-ts-app --typescript
┌ Vue.js - The Progressive JavaScript Framework
│
◇ Select features to include in your project:
│ TypeScript
Scaffolding project in /home/me/my-ts-app...
│
└ Done. Now run:
cd my-ts-app
npm install
npm run dev
Then add lang="ts" to the script block of each component:
<script setup lang="ts">
import { ref } from 'vue'
const count = ref(0) // Ref<number>, inferred
</script>| Tool | Role |
|---|---|
vue-tsc |
Type-checks .vue files on the command line (npm run type-check) |
| Vue - Official (VS Code) | Types, errors and autocompletion inside templates |
| Vite | Strips types while building (it does not type-check) |
Typing props and emits
With <script setup lang="ts">, props and emits are declared with type arguments — no runtime objects needed:
<script setup lang="ts">
interface Product {
id: number
name: string
price: number
}
const props = defineProps<{
product: Product
quantity?: number // optional
}>()
const emit = defineEmits<{
add: [id: number, qty: number] // event name → argument list
remove: [id: number]
}>()
function addToCart() {
emit('add', props.product.id, props.quantity ?? 1)
// emit('add', 'oops') ❌ Argument of type 'string' is not assignable to 'number'
}
</script>Default values for optional props come from destructuring (Vue 3.5) or withDefaults:
const { quantity = 1 } = defineProps<{ product: Product; quantity?: number }>()
// or, before 3.5:
const props = withDefaults(defineProps<{ quantity?: number }>(), { quantity: 1 })The runtime equivalent in JavaScript, runnable here:
<div id="app">
<product-row v-for="p in products" :key="p.id" :product="p" :quantity="2" @add="onAdd"></product-row>
<p>Cart: {{ cart.join(', ') || 'empty' }}</p>
</div>
<script type="module">
import { createApp, ref } from 'vue';
const app = createApp({
setup() {
const products = [{ id: 1, name: 'Mug', price: 8 }, { id: 2, name: 'T-shirt', price: 15 }];
const cart = ref([]);
const onAdd = (id, qty) => { cart.value.push(`${qty}× #${id}`); };
return { products, cart, onAdd };
}
});
app.component('product-row', {
// runtime declaration = what defineProps<…>() compiles to
props: {
product: { type: Object, required: true },
quantity: { type: Number, default: 1 }
},
emits: {
add: (id, qty) => typeof id === 'number' && typeof qty === 'number'
},
template: `
<p>{{ product.name }} — \${{ product.price }}
<button @click="$emit('add', product.id, quantity)">Add {{ quantity }}</button></p>`
});
app.mount('#app');
</script>Typing refs, reactive and computed
Types are usually inferred from the initial value. Pass a type argument when the initial value doesn't tell the whole story:
import { ref, reactive, computed } from 'vue'
import type { Ref } from 'vue'
const count = ref(0) // Ref<number>
const user = ref<User | null>(null) // starts null, later a User
const ids: Ref<number[]> = ref([])
interface Todo { id: number; text: string; done: boolean }
const state = reactive<{ todos: Todo[]; filter: 'all' | 'open' }>({ todos: [], filter: 'all' })
const openCount = computed(() => state.todos.filter(t => !t.done).length) // ComputedRef<number>Template refs and events
import { useTemplateRef, onMounted } from 'vue'
const input = useTemplateRef<HTMLInputElement>('input') // Vue 3.5
onMounted(() => input.value?.focus())
function onChange(event: Event) {
console.log((event.target as HTMLInputElement).value)
}Typing provide/inject
InjectionKey carries the type from provide to inject:
// keys.ts
import type { InjectionKey, Ref } from 'vue'
export const ThemeKey: InjectionKey<Ref<'light' | 'dark'>> = Symbol('theme')
// provider
provide(ThemeKey, theme)
// consumer
const theme = inject(ThemeKey) // Ref<'light' | 'dark'> | undefinedTypes help even in JavaScript
Even without TypeScript, runtime prop validation catches mistakes in development. This playground's validator rejects a wrong status, and the component falls back gracefully:
<div id="app">
<status-pill status="online"></status-pill>
<status-pill status="away"></status-pill>
<status-pill status="sleeping"></status-pill>
</div>
<script type="module">
import { createApp } from 'vue';
const COLORS = { online: '#22c55e', away: '#f59e0b', offline: '#9ca3af' };
const app = createApp({});
app.component('status-pill', {
props: {
status: {
type: String,
default: 'offline',
validator: (v) => {
const ok = v in COLORS;
if (!ok) console.log(`status-pill: "${v}" is not one of ${Object.keys(COLORS).join(', ')}`);
return ok;
}
}
},
template: `
<span :style="{ background: COLORS[status] || COLORS.offline, color: 'white', padding: '2px 10px', borderRadius: '10px', marginRight: '6px' }">
{{ status }}
</span>`,
setup: () => ({ COLORS })
});
app.mount('#app');
</script>In TypeScript you'd write status?: 'online' | 'away' | 'offline', and status="sleeping" would be a compile error in your editor before you ever run the page.
Tip: Run
vue-tsc --noEmitin CI (the scaffold'stype-checkscript does this). Vite's dev server skips type checking for speed, so errors only show in your editor unless you check explicitly.
Note: The Options API can be typed too: wrap the options object in
defineComponent({ … })to get inference forthis. The Composition API with<script setup lang="ts">gives the best results with the least effort.
Test yourself
How do you enable TypeScript in a Single-File Component?
- Rename it to
.vue.ts - Add
lang="ts"to the<script>tag - Import
typescriptin main.js - It is always on
Which tool type-checks .vue files from the command line?
vite buildvue-tsctscaloneeslint
What type does const user = ref<User | null>(null) have?
UsernullRef<User | null>any