如何在 TypeScript 中检查类类型:instanceof、类型守卫和类型保护
大家好!我是 TypeScript 新手,遇到了类类型检查的问题。我有一个类层次结构:基类 `Animal` 和两个子类 `Dog` 和 `Cat`。每个子类都有自己的独特方法:`Dog` 的 `bark()` 和 `Cat` 的 `meow()`。
我从外部源(例如 API)获取一个 `Animal[]` 类型的对象数组,需要确定每个对象具体属于哪个类,以便调用相应的方法。
以下是代码示例:
```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 Dog('Rex'), new Cat('Molly')];
animals.forEach(animal => {
// 如何检查 animal 是 Dog 还是 Cat?
// if (animal instanceof Dog) { ... } — 这能工作吗?
// 还是需要使用 t