Course contentsShow
← TypeScript
Lesson 215 of 1,7965. Type Narrowing FundamentalsFree lesson

Narrowing Class Hierarchies with instanceof

Using 'instanceof' to narrow from a base class or interface to derived classes in inheritance hierarchies.

Narrowing Class Hierarchies with instanceof

You'll learn: How to use instanceof to narrow from a base class or interface to specific derived classes in inheritance hierarchies.

The Core Idea

When you have a variable typed as a parent class (or a union of related classes), TypeScript doesn't automatically know which specific subclass you're working with. The instanceof operator lets you check if an object is an instance of a particular class, and TypeScript uses that check to narrow the type to that subclass, giving you access to its specific properties and methods.

How It Works

Think of a class hierarchy like a family tree. If you know someone is "a person," you don't know if they're a teacher or a doctor. But once you check if (person instanceof Teacher), you can safely access teacher-specific properties.

class Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

class Dog extends Animal {
  bark() {
    console.log("Woof!");
  }
}

class Cat extends Animal {
  meow() {
    console.log("Meow!");
  }
}

function makeSound(animal: Animal) {
  if (animal instanceof Dog) {
    // TypeScript knows: animal is Dog here
    animal.bark();
  } else if (animal instanceof Cat) {
    // TypeScript knows: animal is Cat here
    animal.meow();
  }
}

Inside each if block, TypeScript has narrowed the Animal type down to the specific subclass, so you can safely call methods unique to Dog or Cat.

Why This Matters

Without instanceof, TypeScript only knows about properties shared by all subclasses. The narrowing unlocks subclass-specific behavior safely, without type assertions.

Key Takeaway: Use instanceof to narrow from parent classes to child classes in inheritance hierarchies, giving TypeScript enough information to safely access subclass-specific properties and methods.