Senior LevelJavaScript & TypeScript
What are TypeScript discriminated unions and exhaustive type checks?
❓ Interview Prompt: Explain tagged unions, narrowing with switch/if, and the never type for compile-time exhaustiveness.
Discriminated unions (tagged unions) are union types where each member has a common literal property (the "discriminant") that TypeScript uses for automatic type narrowing.
Pattern:
1
Each union member has a shared property with a unique literal value.
2
TypeScript narrows the type inside switch/if blocks based on the discriminant.
3
The
never type in the default case ensures compile-time exhaustiveness: if you add a new union member and forget to handle it, TypeScript reports an error.Code Implementation Example
typescript
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rectangle'; width: number; height: number }
| { kind: 'triangle'; base: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'rectangle':
return shape.width * shape.height;
case 'triangle':
return (shape.base * shape.height) / 2;
default:
// Exhaustive check: compile error if any Shape member is unhandled!
const _exhaustiveCheck: never = shape;
throw new Error(`Unhandled shape: ${_exhaustiveCheck}`);
}
}💡Discriminated union with exhaustive switch/case and never type guard.
🎯 Interview Key Takeaway
Use discriminated unions with a never default case to get compile-time errors when a new union member is not handled.
#Discriminated Unions#Exhaustive#Type Safety#Senior
Back to all JavaScript & TypeScript Questions→