MST

星途 面试题库

面试题:TypeScript类多态的基础实现

请使用TypeScript实现一个简单的多态示例,至少包含一个基类和两个继承自该基类的子类。在子类中重写基类的一个方法来展示多态特性,并编写代码调用这些方法以体现多态效果。
19.1万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 基类
class Animal {
    makeSound(): void {
        console.log('动物发出声音');
    }
}

// 子类1
class Dog extends Animal {
    makeSound(): void {
        console.log('汪汪汪');
    }
}

// 子类2
class Cat extends Animal {
    makeSound(): void {
        console.log('喵喵喵');
    }
}

// 展示多态效果
function makeAnimalSound(animal: Animal) {
    animal.makeSound();
}

const dog = new Dog();
const cat = new Cat();

makeAnimalSound(dog);
makeAnimalSound(cat);