← 返回完整题库
Typescript中等

如何在TypeScript中实现继承?

参考答案

继承方式一:ES6 class + extends

class Animal {
  constructor(public name: string) {}
  speak(): string { return `${this.name} 叫`; }
}

class Dog extends Animal {
  constructor(name: string, public breed: string) {
    super(name);              // 必须先调用 super 才能用 this
  }
  override speak(): string {
    return super.speak() + ':汪汪';
  }
}

方式二:接口继承

interface Base { id: number }
interface User extends Base { name: string }        // 接口继承
class Person implements User { id = 1; name = 'a'; } // 类实现接口

方式三:原型继承(ES5 风格,仍可用)

function Animal(this: any, name: string) { this.name = name; }
Animal.prototype.speak = function () { return this.name; };
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

方式四:抽象类

abstract class Shape {
  abstract area(): number;         // 子类必须实现
  describe() { return `面积 ${this.area()}`; }
}
class Circle extends Shape {
  constructor(private r: number) { super(); }
  area() { return Math.PI * this.r ** 2; }
}

关键点

  1. extends 继承实现与类型;implements 只做类型检查,不影响运行时。
  2. 子类构造器里**必须先 super()**,否则访问 this 报错。
  3. 支持多接口实现(implements A, B),但类只能单继承。
  4. override 修饰符 + noImplicitOverride 可避免"假重写"。
  5. 访问修饰符只能放宽不能收紧(protected 不能改成 private)。
  6. 静态成员通过 super.staticMethod() 访问父类静态成员。

本题来自 计算机知识面试题库,共 921 道题。