TypeScript with Vue

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…

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>
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 },
)

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>

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'.

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>

⚠️ What makes vue-tsc complain, and what isn't checked at all

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.

What you will learn