Narrowing with switch Statements
You'll learn how to use switch statements on discriminant properties to safely narrow union types to their specific variants.
The Core Idea
When you have a discriminated union, you can use a switch statement on the discriminant property to narrow each case to its specific type. TypeScript's control flow analysis recognizes switch statements and understands that inside each case block, you're dealing with only one variant of the union.
This creates clean, readable code where each case handles exactly one shape from your union, and TypeScript knows precisely which properties are available.
How It Works
After learning about discriminant properties, you now have unions where each variant has a unique literal value in a shared property. The switch statement tests that discriminant, and TypeScript narrows accordingly:
type Success = { status: 'success'; data: string };
type Loading = { status: 'loading' };
type Error = { status: 'error'; message: string };
type Result = Success | Loading | Error;
function handleResult(result: Result) {
switch (result.status) {
case 'success':
// TypeScript knows: result is Success here
console.log(result.data);
break;
case 'loading':
// TypeScript knows: result is Loading here
console.log('Loading...');
break;
case 'error':
// TypeScript knows: result is Error here
console.log(result.message);
break;
}
}
Each case branch has access to only the properties specific to that variant. No type assertions needed—TypeScript does the narrowing automatically.
Key Takeaway: Using switch on the discriminant property gives you automatic, safe narrowing to each union variant in its corresponding case block, making discriminated unions incredibly powerful for handling different shapes of data.