MST

星途 面试题库

面试题:TypeScript类型保护在类继承结构中的应用

定义一个父类`Animal`,有一个方法`makeSound`。再定义两个子类`Dog`和`Cat`,分别重写`makeSound`方法。现在有一个数组`let animals: Animal[] = [new Dog(), new Cat()];`,编写一个函数`getDogSounds`,使用类型保护,从`animals`数组中获取所有`Dog`实例发出的声音并返回。
25.9万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
class Animal {
    makeSound() {
        return 'Generic animal sound';
    }
}

class Dog extends Animal {
    makeSound() {
        return 'Woof!';
    }
}

class Cat extends Animal {
    makeSound() {
        return 'Meow!';
    }
}

function getDogSounds(animals: Animal[]): string[] {
    return animals.filter((animal): animal is Dog => animal instanceof Dog)
                  .map(animal => animal.makeSound());
}

let animals: Animal[] = [new Dog(), new Cat()];
console.log(getDogSounds(animals));

上述代码解释如下:

  1. 定义了父类Animal,包含makeSound方法。
  2. 定义了子类DogCat,都重写了makeSound方法。
  3. getDogSounds函数通过filter方法和类型保护animal instanceof Dog筛选出animals数组中的Dog实例,然后使用map方法获取这些Dog实例发出的声音并返回。