Empty Union Resolution
What you'll learn: How narrowing all possibilities out of a union type leaves you with never.
The Core Idea
When TypeScript analyzes your code, it uses control flow analysis to eliminate impossible cases from union types. If you write enough type guards to rule out every member of a union, TypeScript recognizes that the code path is unreachable and assigns the type never to represent "no possible value can exist here."
This isn't a bug—it's TypeScript proving mathematically that your code can't be reached.
How Union Elimination Works
Imagine you have a union type representing a traffic light:
type TrafficLight = "red" | "yellow" | "green";
As you check each possibility with if statements, TypeScript removes the checked values from the union:
function handleLight(light: TrafficLight) {
if (light === "red") {
// light is "red" here
return "stop";
}
if (light === "yellow") {
// light is "yellow" here
return "slow down";
}
if (light === "green") {
// light is "green" here
return "go";
}
// What type is light here?
// TypeScript has eliminated all three possibilities
light; // Type: never
}
After all three checks, there are no remaining members of the union. TypeScript resolves this empty union to never.
Why This Matters
Empty union resolution is the foundation of exhaustiveness checking. When you've handled every case in a discriminated union, the else branch becomes never, proving your logic is complete:
type Result = { success: true; data: string } | { success: false; error: string };
function handle(result: Result) {
if (result.success) {
return result.data;
} else {
return result.error;
}
// Unreachable: result is never here
result; // Type: never
}
The Analogy
Think of a union type as a checklist of possibilities. Each type guard crosses off one item. When you've crossed off everything on the list, you're left with an empty list—that's never. It's TypeScript's way of saying "you've thought of everything; nothing else is possible."
Key Takeaway: When control flow narrowing eliminates all members of a union type, TypeScript resolves the remaining type to never, proving that code path is unreachable.