TypeScript Type Narrowing
Narrowing is the process by which TypeScript refines a broader type (like a union) down to a more specific type based on checks in your code, such as `typeof` or `instanceof`.
As you narrow a value's type inside an `if` statement or similar control flow, TypeScript automatically updates what operations are allowed on that value within that block of code.
if (typeof value === "string") {
// value is string here
}typeof narrowing
Checking `typeof value === "string"` narrows a union like `string | number` down to just `string` inside that branch, allowing string-only methods safely.
instanceof narrowing
For classes, `value instanceof ClassName` narrows the type to that specific class inside the matching branch, useful when working with multiple related class types.
function printLength(value: string | number) {
if (typeof value === "string") {
console.log(value.length);
} else {
console.log(value.toFixed(0));
}
}
printLength("hello");
printLength(3.7);5
4Inside each branch, TypeScript narrows value to either string or number based on the typeof check.
class Cat { meow() { return "Meow"; } }
class Dog { bark() { return "Woof"; } }
function speak(animal: Cat | Dog) {
if (animal instanceof Cat) {
console.log(animal.meow());
} else {
console.log(animal.bark());
}
}
speak(new Cat());Meowinstanceof narrows animal to Cat inside the if branch, allowing meow() to be called safely.
Key points
- Narrowing refines a broad type down to a more specific one within a code branch.
- typeof narrowing works for primitive types like string, number, and boolean.
- instanceof narrowing works for class instances.
- TypeScript automatically tracks narrowed types inside if/else branches.
