Concept Explanation
Say a value could be a string | number. Inside your function you can't call .toUpperCase() on it — TypeScript stops you, because numbers don't have that method. Narrowing is how you prove to the compiler "in this branch, it's definitely a string," unlocking the string methods safely.
It's a conversation: you write an if check, TypeScript follows your logic, and inside the block it narrows the type automatically. This "control-flow analysis" is one of TypeScript's smartest features.
Syntax or Core Structure
function format(value: string | number) {
if (typeof value === "string") {
return value.toUpperCase(); // TS knows it's a string here
}
return value.toFixed(2); // ...and a number here
}
Other narrowing tools:
if (pet instanceof Dog) pet.bark(); // class check
if ("wings" in animal) animal.fly(); // property check
if (value !== null) value.trim(); // null guard
Real World Example
Discriminated Unions: Give each shape a shared "tag" and TS narrows on it:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
function area(s: Shape) {
if (s.kind === "circle") return Math.PI * s.radius * s.radius;
return s.side * s.side; // TS knows it's a square
}
Common Mistakes
- Trusting any:
anyskips narrowing entirely — you lose all the safety. - Forgetting the null Case: With
stricton, TS forces you to guardnull/undefinedbefore use. - Wide Return Types: If a function can return several shapes, model them as a union so callers can narrow.
Best Practices
- Tag Your Unions: A shared
kindfield makes narrowing trivial and exhaustive. - Use Type Guards: For reusable checks, write a function returning
x is Dog(a "type predicate"). - Handle Every Branch: Add a
defaultthat assigns toneverso a new variant becomes a compile error.
Practice Exercises
- The Formatter: Write a function taking
string | numberthat upper-cases strings and rounds numbers. - The Shape: Build a discriminated union of "circle" and "rectangle" and compute each area.
- The Guard: Write a type predicate
isString(x): x is stringand use it to narrow anunknown.