Skip to content
dreamcode
dreamcode
Map
Unions
Lesson 7 of 26
+15 XP on finish
TYPESCRIPTChapter 2 · TS Unions & Enums

Unions and Type Narrowing

A Union Type (A | B) allows a variable to hold values of multiple types. To safely interact with the value, you use Type Narrowing via conditionals to isolate the active type.

Worked example

How it reads

  • string | number allows id to be either a string or a number
  • typeof id === 'string' acts as a type guard to narrow the type
Cloud tip: Type guards like typeof or instanceof allow safe, type-specific code execution.
index.ts
TYPESCRIPT
type-checked, then run in your browser
Console
Run your code to see its output here.
YOUR TURN

Add boolean to the union and handle it by logging on for true and off for false. Call processSignal(true).

Press Run to check your work.