Type Guards help you safely narrow down types in conditional blocks, so TypeScript knows exactly what you're working with.
value is Type to tell TypeScript about type narrowing.
typeof, instanceof, or custom type guard functions.paramName is Type.
class Dog {
bark() {
console.log("Woof!");
}
}
class Cat {
meow() {
console.log("Meow!");
}
}
function speak(animal: Dog | Cat) {
if (animal instanceof Dog) {
animal.bark();
} else {
animal.meow();
}
}
speak(new Dog());
speak(new Cat());