TypeScript ยท Chapter 32 of 44

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.

Syntax
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.

Example 1 (typescript)
function printLength(value: string | number) {
  if (typeof value === "string") {
    console.log(value.length);
  } else {
    console.log(value.toFixed(0));
  }
}
printLength("hello");
printLength(3.7);
Output
5
4

Inside each branch, TypeScript narrows value to either string or number based on the typeof check.

Example 2 (typescript)
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());
Output
Meow

instanceof 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.
๐Ÿ’ก Note: Narrowing is what makes union types practical and safe to use in real code.

๐Ÿ“ Quick Quiz

1. What is type narrowing?

2. Which operator narrows primitive types like string vs number?

3. Which operator narrows class instances?