TypeScript中的类类型检查:如何判断对象是否为特定类的实例?
大家好!我最近开始学习TypeScript,在运行时进行类型检查时遇到了一个问题。
我有一个类层次结构:
```typescript
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
}
class Dog extends Animal {
bark() {
console.log("Woof!");
}
}
class Cat extends Animal {
meow() {
console.log("Meow!");
}
}
```
我正在编写一个函数,它接收一个 `Animal[]` 数组,并希望对狗和猫执行不同的操作。在JavaScript中,我会使用 `instanceof`,但当我尝试这样做时,TypeScript会报错:
```typescript
function processAnimals(animals: Animal[]) {
for (const animal of animals) {
if (animal instanceof Dog) { // 错误:'Dog' 引用了一个值,但在这里被用作类型
animal.bark();
} else if (animal instanceof Cat) {
animal.meow();
}
}
}
```
TypeScript提示:`'Dog' refers to a value, but is being used as a type here`