Remember price="15" without the colon in the Props lesson? Without the colon, text is sent, so the card said Takeaway: $152. In the exercise editor, that odd number was your only clue. A mistake like that can actually be found before the page is ever opened.
The way to do it is TypeScript: JavaScript with notes about types added. A type is the kind of value that may be used, such as text or a number, like type: Number in the Props lesson. In Vue, you write <script setup lang="ts">, then state the shape of props, emits and refs as types. Before the app runs, a tool called vue-tsc checks the script and the template.
Picture an order form at Mrs. Sri's stall where each box has a label: "menu name (text)", "price (number)". The cashier checks the form at the front counter. An order with "fifteen dollars" in the number box is refused at that counter, not discovered once the plate has reached the customer's table. The form is your code, and the label on each box is a type. The cashier is vue-tsc, and the kitchen is the browser that runs the app.
lang="ts" and type-based defineProps
This is MenuCard.vue written with TypeScript:
<!-- src/components/MenuCard.vue -->
<script setup lang="ts">
const props = defineProps<{
name: string
price: number
stock?: number
}>()
const emit = defineEmits<{
add: [name: string, price: number]
}>()
function clickAdd() {
emit("add", props.name, props.price)
}
</script>
lang="ts"turns on TypeScript in that script block.defineProps<{ ... }>()declares props through a type only. The type goes between< >after the function name, and the parentheses stay empty. A function that takes a type between< >, not only values, is called generic.name: stringis a type annotation: the name, a colon, then the type. TypeScript types are lowercase:string(text),number,boolean(true or false).?means optional:stock?: numbermay be left out, and its value is thenundefined.- Vue's compiler turns that type into an ordinary props declaration. This is the compiled output of the
MenuCard.vueabove:
props: {
name: { type: String, required: true },
price: { type: Number, required: true },
stock: { type: Number, required: false }
},
emits: ["add"],
So in development mode, Vue still checks props while the app runs, as in the Props lesson.
Defaults and typed emits
Defaults for type-based props are written with withDefaults:
const props = withDefaults(
defineProps<{ name: string; price: number; stock?: number }>(),
{ stock: 0 },
)
withDefaultswrapsdefineProps, sostockbecomes 0 when it isn't sent. It compiles tostock: { type: Number, required: false, default: 0 }.- Since Vue 3.5, a default can also be written while destructuring the props:
const { name, price, stock = 0 } = defineProps<{ ... }>(). It compiles to the same thing. defineEmits<{ add: [name: string, price: number] }>()declares theaddevent with two payloads, in order: text, then a number. The square brackets hold the list of payloads. The older form that means the same:defineEmits<{ (e: "add", name: string, price: number): void }>()(voidmeans it returns nothing).defineProps<...>()can't also take a normal argument inside its parentheses.defineProps<{ name: string }>({ name: String })fails to compile withdefineProps() cannot accept both type and non-type arguments at the same time. Use one or the other.
Typed refs
Refs have types too. The comments in this code name them:
const count = ref(0) // Ref<number>, inferred from 0
const last = ref<number | null>(null) // a number, or null before any order
const cart = ref<{ name: string; price: number }[]>([])
const total = computed(() => cart.value.reduce((a, i) => a + i.price, 0)) // ComputedRef<number>
- When the starting value is clear, TypeScript infers (guesses) the type from it by itself:
ref(0)becomesRef<number>, a ref that holds a number. ref(null)is inferred asRef<null>, a ref that may only holdnull. Solast.value = priceis refused. Write the type between< >:ref<number | null>(null). The|sign means "or": a number ornull.- An empty array needs a type too, because TypeScript can't infer what goes in
ref([]). In that code,{ name: string; price: number }[]means an array of objects that have aname(text) and aprice(a number).
What vue-tsc catches
A TypeScript project from create-vue has a type-check command (listed in package.json) that runs vue-tsc --build. This is its real output for price="15" (a long type is shortened here to ...):
$ npm run type-check
> [email protected] type-check
> vue-tsc --build
src/App.vue:16:31 - error TS2322: Type 'string' is not assignable to type 'number'.
16 <MenuCard name="Fried Rice" price="15" :stock="8" @add="addToCart" />
~~~~~
src/components/MenuCard.vue:4:3
4 price: number
~~~~~
The expected type comes from property 'price' which is declared here on type '{ readonly name: string; ... }'
Found 1 error.
src/App.vue:16:31 means the file, the line, then the column. TS2322 is the number of that kind of error, and the message means: text can't be used where the type is a number. The part below it points to where that type is written: price: number in MenuCard.vue. vue-tsc refuses it before the page has ever been opened. Other mistakes vue-tsc finds:
| Mistake | vue-tsc message |
|---|---|
<MenuCard :price="15" /> without name |
error TS2345: ... followed by Property 'name' is missing in type '{ price: number; ... }' |
emit("add", props.price, props.name) |
error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. |
emit("ad", props.name, props.price) |
error TS2345: Argument of type '"ad"' is not assignable to parameter of type '"add"'. |
const last = ref(null) then last.value = price |
error TS2322: Type 'number' is not assignable to type 'null'. |
npm run devdoes not check types. Vite only strips the types, then runs the JavaScript. So an app full of type errors still opens. The type check runs innpm run type-check, and in a create-vue project,npm run buildruns it too.- TypeScript can't check data that only arrives while the app runs, such as a
fetchresult from the server.
In the exercise editor
In the exercise, one editor holds two .vue files: ProfileCard.vue and App.vue. Each file starts with the line <!-- FileName.vue -->. The editor compiles both with the same Vue compiler that Vite uses (@vue/compiler-sfc). So <script setup lang="ts"> and defineProps<...>() work as in a real project. This is ProfileCard.vue when it's done:
<!-- ProfileCard.vue -->
<script setup lang="ts">
defineProps<{
name: string
age: number
}>()
</script>
<template>
<div>
<h2 id="name">{{ name }}</h2>
<p id="age">{{ age }} years old</p>
</div>
</template>
- The compiler turns
defineProps<{ name: string; age: number }>()intodefineProps({ name: { type: String, required: true }, age: { type: Number, required: true } }), then removes the types before it runs. App.vueimportsProfileCard.vueand sendsname="Budi"and:age="17", so it shows<h2 id="name">Budi</h2>and<p id="age">17 years old</p>.- Like
npm run dev, this editor doesn't check types:age="17"(text, not a number) still shows. Onlyvue-tscrefuses it.
⚠️ What makes vue-tsc complain, and what isn't checked at all
price="15"without the colon sends text, andvue-tscrefuses it with TS2322. Write:price="15".ref(null)orref([])with no type makes TypeScript lock the type tonullor an empty array. Writeref<number | null>(null).npm run devdoesn't check types. Runnpm run type-check, or install the Vue extension in your code editor so errors show right away.- In the exercise, the code must contain
lang="ts", anddefineProps<withname: stringandage: number.#namemust holdBudi, and#agemust hold17 years old.
TL;DR: TypeScript is JavaScript with notes about types added (the kind of value, such as string for text and number for a number). <script setup lang="ts"> turns on TypeScript in a .vue file. Props are declared through a type written between < >: defineProps<{ name: string; price: number; stock?: number }>(), with ? for an optional prop. Defaults are given through withDefaults, or stock = 0 while destructuring the props (Vue 3.5 and later). Events are declared through defineEmits<{ add: [name: string, price: number] }>(). Vue's compiler turns those types into an ordinary props declaration, which is used while the app runs. The type of ref(0) is inferred, but ref(null) needs to be written ref<number | null>(null). vue-tsc (through npm run type-check) finds a prop of the wrong type, a required prop that isn't sent, and an emit with the wrong name or order, before the browser runs anything. npm run dev doesn't check types. The exercise editor compiles <script setup lang="ts"> the way Vite does: types become props, then are removed without being checked.
⚡ lang="ts" and props through a type
Write:
<script setup lang="ts">
const props = defineProps<{
name: string
price: number
stock?: number
}>()
const emit = defineEmits<{
add: [name: string, price: number]
}>()
</script>
Meaning: lang="ts" turns on TypeScript (JavaScript with notes about types) in that script block. defineProps<{ ... }>() declares props through a type only: the type goes between < >, and the parentheses stay empty. name: string means the prop name is text, and price: number means it is a number. ? means optional. defineEmits declares the add event with two payloads: text, then a number. Vue's compiler turns that type into an ordinary props declaration.
⚡ Refs that need a type
Write:
const count = ref(0)
const last = ref<number | null>(null)
Guess first: vue-tsc is a type checker for Vue. If you write const last = ref(null), then last.value = price (a number), what does vue-tsc say?
It's refused: Type 'number' is not assignable to type 'null'. That means a number can't go where the type is null. ref(null) is inferred as Ref<null>.
Meaning: When the starting value is clear, as in ref(0), TypeScript infers the type itself. null or an empty array needs a type between < >. number | null means a number or null.
⚡ npm run dev doesn't check types
Write:
npm run type-check
Guess first: the prop price has the type number, but it's written price="15" with no colon, so text is sent. Does the app fail to run under npm run dev?
No, it still opens. Vite only strips the types, then runs the JavaScript.
Meaning: This runs vue-tsc, which refuses price="15" with error TS2322 before the page has ever been opened.