Type Narrowing
ELI5 — The Vibe Check
Type narrowing is TypeScript being a detective. It watches your if-statements and logical checks, then deduces 'ah, at this point in the code, this variable MUST be a string.' It's Sherlock Holmes but for types.
Real Talk
The process by which TypeScript's control flow analysis refines a variable's type to a more specific type based on conditional checks, assignments, and type guard expressions. Type narrowing happens automatically within if/else blocks, switch statements, and after truthiness checks.
Show Me The Code
function format(value: string | number | null) {
if (value === null) return 'N/A';
// narrowed to string | number
if (typeof value === 'string') {
return value.trim(); // narrowed to string
}
return value.toFixed(2); // narrowed to number
}
When You'll Hear This
"TypeScript's narrowing is smart enough to know that after a null check, the value can't be null." / "Use discriminated unions with narrowing — it's the TypeScript sweet spot."
Related Terms
Discriminated Union
A discriminated union is like a box that could contain a cat, a dog, or a fish — but it has a label on the outside telling you which one.
Type Guard
A type guard is like a bouncer at a club checking IDs. Before your code enters the VIP section, the guard checks 'are you a string or a number?
TypeScript
TypeScript is JavaScript with a strict parent watching over it.