Manuals / TypeScript / Chapter 4
B · Modeling · intermediate · Week 2 · Chapter 4 of 11
Unions, narrowing & discriminated unions
Union types model "A or B". Narrowing refines unions with typeof, instanceof, in, and truthiness checks. Discriminated unions add a shared literal field for exhaustive switch — the pattern for API states and UI machines.
Path progress29%
Step 1 of 5
Basic unions
type Id = string | number. Functions accepting unions must handle all cases or narrow first.
Do this now
Write formatId(id: string | number): string handling both.
Was this step clear?
Chapter learning outcomes
- Union types
- Type narrowing
- Discriminated unions
- Exhaustiveness checking
- never type
Clear these before you leave
Side quest
UI state machine
Type a modal flow: closed | confirming | submitting | success | error. One renderModal(state) with exhaustive switch.