Skip to content
dreamcode
dreamcode
Map
Type guards
Lesson 8 of 26
+15 XP on finish
TS UNIONSChapter 2 · TS Unions & Enums

Type Guards

TypeScript narrows a union whenever you check it: typeof x === "string", "swim" in pet, or value instanceof Date. When the check is too involved for that, write a type guard: a function whose return type is pet is Fish. Wherever it returns true, TypeScript treats the value as a Fish.

Worked example

How it reads

  • pet is Fish tells TypeScript what a true result means
  • In the true branch, pet.swim() is allowed; in the false branch, only Bird is left
  • "swim" in pet checks for the property at run time
Cloud tip: A type guard is only as honest as its body. If the check is wrong, TypeScript will trust it anyway.
index.ts
TYPESCRIPT
type-checked, then run in your browser
Console
Run your code to see its output here.
YOUR TURN

Write a type guard isNumber(r: Reading): r is number. Make toCelsius return numbers unchanged and parse text like "19C" with parseFloat, returning a number. Log toCelsius("19C") + 1: 20.

Press Run to check your work.