Avatar ·

How to check class type in TypeScript: instanceof, type guards and type protection

Hello everyone! I'm new to TypeScript and I've encountered a problem with checking class types. I have a class hierarchy: a base class `Animal` and two child classes — `Dog` and `Cat`. Each of them has its own unique methods: `bark()` for Dog and `meow()` for Cat. I receive an array of `Animal[]` type objects from an external source (e.g., API), and I need to determine which specific class each object belongs to in order to call the corresponding method. Here's an example code: ```typescript class Animal { name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { bark() { console.log(`${this.name} says: Woof!`); } } class Cat extends Animal { meow() { console.log(`${this.name} says: Meow!`); } } const animals: Animal[] = [new