Middle
TypeScript task: there is a class Animal with methods move and bark, the function process takes an animal of type Animal and calls its bark method. Will there be a TypeScript error? How to narrow the type correctly? How to write a type guard?
sobes.tech AI
Answer from AI
If the Animal class has methods move and bark, and the process function takes a parameter of type Animal and calls bark, there will be no TypeScript error if bark is defined in Animal.
However, if bark is not present in all animals (for example, only in dogs), and Animal is a base class without bark, then there will be an error because the method might be missing.
To correctly narrow the type and call bark, you need to use a type guard — a function that checks whether the object indeed has the bark method.
Example:
class Animal {
move() {
console.log('Moving');
}
}
class Dog extends Animal {
bark() {
console.log('Woof!');
}
}
function isDog(animal: Animal): animal is Dog {
return (animal as Dog).bark !== undefined;
}
function process(animal: Animal) {
if (isDog(animal)) {
animal.bark(); // now safe
} else {
console.log('This is not a dog');
}
}
const dog = new Dog();
process(dog); // Woof!
const animal = new Animal();
process(animal); // This is not a dog
Here, isDog is a type guard that checks for the presence of the bark method and narrows the type of animal to Dog within the if block.