Typescript instanceof guard
Created By: chatGPT
In TypeScript, the
instanceof
operator is a powerful tool for type guards. It allows you to check if an object is an instance of a particular class or interface. This is especially useful when you're working with polymorphic types and need to narrow down the type of an object dynamically. Here’s how you can create an instanceof
guard to differentiate between types.// Define a base class
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
}
// Define subclasses
class Dog extends Animal {
bark() {
console.log(`${this.name} says Woof!`);
}
}
class Cat extends Animal {
meow() {
console.log(`${this.name} says Meow!`);
}
}
// Create a type guard function using instanceof
function isDog(animal: Animal): animal is Dog {
return animal instanceof Dog;
}
function processAnimal(animal: Animal) {
if (isDog(animal)) {
animal.bark(); // animal is inferred as Dog
} else {
animal.meow(); // Otherwise, it’s a Cat
}
}
// Usage example
const myDog = new Dog('Buddy');
const myCat = new Cat('Whiskers');
processAnimal(myDog); // Outputs: Buddy says Woof!
processAnimal(myCat); // Outputs: Whiskers says Meow!