Course contentsShow
← TypeScript
Lesson 397 of 1,7969. Union TypesFree lesson

instanceof for Class Unions

Using instanceof to narrow unions of class instances to specific subtypes.

instanceof for Class Unions

What you'll learn: How to use instanceof to narrow union types when working with class instances.

The Core Idea

When you have a union of different class instances, TypeScript doesn't automatically know which specific class you're working with at any given moment. The instanceof operator lets you check if a value was created from a specific class constructor, and TypeScript's control flow analysis uses this information to narrow the union to that specific class type.

This is especially useful when different classes in your union have different properties or methods that you want to access safely.

How It Works

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

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

type Pet = Dog | Cat;

function makeSound(pet: Pet) {
  // pet is Dog | Cat here
  
  if (pet instanceof Dog) {
    // TypeScript narrows: pet is Dog
    pet.bark();
  } else {
    // TypeScript narrows: pet is Cat
    pet.meow();
  }
}

const myDog = new Dog();
const myCat = new Cat();

makeSound(myDog); // "Woof!"
makeSound(myCat); // "Meow!"

The instanceof check examines the prototype chain at runtime, and TypeScript recognizes this pattern to safely narrow your types.

Real-World Pattern

This becomes invaluable when modeling different types of entities that share a common interface but have class-specific behaviors—like different error types, UI components, or data models in your application.

Key Takeaway: Use instanceof to narrow union types of class instances to their specific subtypes, giving you type-safe access to class-specific properties and methods.