A union string | number means “either.” Literal types narrow to exact values: 'GET' | 'POST'.
Combine them for domain states: type Status = 'idle' | 'loading' | 'error'.
Narrowing unions
After checking a discriminant or using typeof, TypeScript shrinks the union so only valid members remain—this is how APIs model finite state machines without enums.
Challenge
Status union
- Type
statusas'draft' | 'published' | 'archived'. - Print the status and whether it equals
published.
Done when: output includes status and a boolean.
Interview prep
- What is a discriminated union?
A union of object types sharing a literal field (e.g.
kind) soswitchcan narrow safely.