Type Narrowing & Discriminated Unions
Type narrowing is the process by which TypeScript reduces a broad union type to a specific, concrete variant based on conditional control flow checks. Narrowing occurs through typeof, instanceof, equality checks, and the in operator.
Discriminated unions (also called tagged unions) represent one of TypeScript's most powerful patterns for state modeling. A discriminated union consists of object variants that share a common literal discriminant property (e.g., kind: 'success' | 'error'). In a switch statement, checking the discriminant allows TypeScript to automatically narrow properties inside each branch.
Exercise
Model an async payment state as a discriminated union (status: 'idle' | 'processing' | 'completed' | 'failed') and write a type-safe handler function.
Check your understanding
What makes a union type 'discriminated'?Show answerHide answer
Answer
A common literal property (the discriminant) present in every variant of the union that TypeScript checks to narrow types.How does exhaustive checking with the never type work?Show answerHide answer
Answer
By assigning unhandled switch default cases to a variable typed as never, TypeScript raises compile errors if a new union variant is added without updating the switch.