TypeScript Fundamentals
Union Types & Narrowing
A union means a value may be one of several types. Narrowing uses runtime checks and control flow to refine what TypeScript knows inside a branch.
- A union requires handling the possibilities
- Runtime checks drive narrowing
- Truthiness narrows but can be too broad
- Narrowing follows control flow
- Assertions bypass narrowing
function printId(id: string | number) {
if (typeof id === "string") {
return id.toUpperCase()
}
return id.toFixed(0)
}| Check | Narrows |
|---|---|
| typeof value === 'string' | Primitive categories |
| value instanceof Error | Class/constructor instances |
| 'kind' in value | Objects with property |
| value.kind === 'success' | Discriminated union variant |
| isUser(value) | Custom type guard |
| assertUser(value) | Assertion function |