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

Combining in and instanceof

Patterns for using both 'in' and 'instanceof' together to narrow complex union types effectively.

Combining in and instanceof

You'll learn: How to use both in and instanceof together to narrow complex union types that require multiple checks.

The Core Idea

Sometimes a single type guard isn't enough. When you have union types involving objects with different properties and different class hierarchies, you need to chain multiple narrowing checks. TypeScript's control flow analysis tracks both in and instanceof checks together, refining the type step-by-step.

Think of it like a security checkpoint: one guard checks your ID (instanceof), another checks your badge (in). Both work together to verify who you are.

How It Works in Practice

You can combine these operators using logical AND (&&) or sequential if statements:

class Dog {
  bark() {}
}

class Cat {
  meow() {}
}

type Pet = Dog | Cat | { type: 'bird'; chirp: () => void };

function handlePet(pet: Pet) {
  if (pet instanceof Dog) {
    pet.bark(); // Narrowed to Dog
  } else if (pet instanceof Cat) {
    pet.meow(); // Narrowed to Cat
  } else if ('chirp' in pet) {
    pet.chirp(); // Narrowed to bird object
  }
}

You can also check properties first, then class instance:

if ('chirp' in pet && pet instanceof Object) {
  // pet is narrowed based on property
}

TypeScript eliminates possibilities with each check, narrowing the remaining union members until you reach specific types.

Key Takeaway: Combine in and instanceof checks sequentially or with logical operators to narrow complex unions that mix plain objects and class instances—TypeScript's control flow analysis tracks both kinds of guards simultaneously.