What Narrowing Means for Unions
You'll learn: How TypeScript automatically refines union types to more specific types as you write conditional logic.
The Core Idea
When you have a union type (like string | number), TypeScript starts by assuming the value could be any of those types. But as you write checks — like typeof guards or truthiness conditions — TypeScript narrows the union down to fewer possibilities within each branch of your code.
Think of it like a sorting machine: you put in mixed items, then as you check "is it metal?" or "is it plastic?", each conveyor belt only carries the items that passed that specific test.
How It Works
function processValue(value: string | number) {
// Here, value is: string | number
if (typeof value === "string") {
// TypeScript narrows to: string
console.log(value.toUpperCase());
} else {
// TypeScript narrows to: number
console.log(value.toFixed(2));
}
}
In the if block, TypeScript knows you've eliminated number from the possibilities — so it treats value as just string. In the else block, the opposite happens: only number remains.
Why This Matters
Without narrowing, you'd have to write awkward type assertions everywhere. Instead, TypeScript's control flow analysis automatically gives you the right autocomplete and safety in each branch.
Key Takeaway: Narrowing transforms broad union types into specific types within conditional branches, giving you type-safe access to the properties and methods of each member type without extra effort.