switch Statements and Union Narrowing
What you'll learn: How TypeScript automatically narrows union types inside each case of a switch statement.
The Power of Switch Cases
When you use a switch statement to check a value that has a union type, TypeScript intelligently narrows the type in each case block. This means inside each case, TypeScript knows exactly which variant of the union you're working with, giving you full autocomplete and type safety.
How It Works
Let's say you have a union type and you switch on a property:
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; size: number };
type Shape = Circle | Square;
function getArea(shape: Shape): number {
switch (shape.kind) {
case "circle":
// Inside here, TypeScript knows shape is Circle
return Math.PI * shape.radius ** 2;
case "square":
// Inside here, TypeScript knows shape is Square
return shape.size ** 2;
}
}
In the "circle" case, shape is narrowed to Circle, so you can safely access .radius. In the "square" case, it's narrowed to Square, giving you access to .size.
Why This Matters
Switch statements provide clean, readable narrowing for discriminated unions. Each case acts like a filter, eliminating all other union variants. This is especially powerful when you have three or more types in your union—much cleaner than chaining multiple if-else statements.
Key Takeaway: TypeScript narrows union types in each case block of a switch statement, giving you precise type information based on the matched value.