How do you narrow a discriminated union inside a switch statement?
Short answer
Switch on the discriminant property; inside each case block, TypeScript automatically narrows the variable to the specific variant matching that case's literal value, giving you safe access to that variant's unique properties.
Advertisement
AModel answer
Switch on the discriminant property; inside each case block, TypeScript automatically narrows the variable to the specific variant matching that case's literal value, giving you safe access to that variant's unique properties.
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle': return Math.PI * shape.radius ** 2; // shape is Circle here
case 'square': return shape.side ** 2; // shape is Square here
}
}Real-world example
Calculating an area, rendering a UI component, or serializing a response differently based on a variant's specific shape.
Likely follow-ups
- Does the same narrowing work with an if/else chain instead of switch?
Related topics