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.


