0
0
Typescriptprogramming~5 mins

instanceof type guards in Typescript

Choose your learning style9 modes available
Introduction

We use instanceof type guards to check what kind of object we have. This helps us use the right properties or methods safely.

When you have a variable that could be one of several object types.
When you want to run different code depending on the object's class.
When you want to avoid errors by checking the object's type before using it.
When working with class instances and need to confirm their type.
When you want clearer and safer code by telling TypeScript the exact type.
Syntax
Typescript
if (variable instanceof ClassName) {
  // code for ClassName objects
}

instanceof checks if the object was created from the given class or its child classes.

This works only with classes, not interfaces or types.

Examples
This checks if pet is a Dog and then calls bark().
Typescript
if (pet instanceof Dog) {
  pet.bark();
}
This runs drive() if vehicle is a Car, otherwise it runs fly().
Typescript
if (vehicle instanceof Car) {
  vehicle.drive();
} else {
  vehicle.fly();
}
Sample Program

This program defines two classes, Cat and Dog. The speak function uses instanceof to check the pet's type and calls the correct sound method.

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

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

function speak(pet: Cat | Dog) {
  if (pet instanceof Cat) {
    pet.meow();
  } else if (pet instanceof Dog) {
    pet.bark();
  }
}

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

speak(myCat);
speak(myDog);
OutputSuccess
Important Notes

instanceof only works with objects created from classes, not plain objects or interfaces.

It helps TypeScript know the exact type inside the if block, so you get better code suggestions and safety.

Summary

instanceof checks an object's class to guide safe code.

Use it when you have multiple possible object types.

It works only with classes, not interfaces or types.