MST
星途 面试题库

面试题:TypeScript 类继承中方法重写的规则及示例

在TypeScript中,阐述类继承时方法重写需要遵循哪些规则,并给出一个简单的示例代码,包括父类定义一个方法,子类重写该方法的完整代码。
47.6万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

方法重写规则

  1. 参数列表和返回类型兼容性:子类重写的方法参数列表必须与父类被重写方法的参数列表兼容,返回类型也必须兼容。通常情况下,返回类型要么与父类方法返回类型相同,要么是其子类型。
  2. 访问修饰符:子类重写方法的访问修饰符不能比父类更严格。例如,如果父类方法是 public,子类重写方法不能是 privateprotected

示例代码

class Animal {
    makeSound(): string {
        return 'Generic animal sound';
    }
}

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

const animal = new Animal();
const dog = new Dog();

console.log(animal.makeSound()); 
console.log(dog.makeSound());