如果我有课程foo

class Foo {
  id: number
  name: string

  sayHi() {
    console.log('hi')
  }
}


如何确保从foo扩展的任何类都必须设置idname的值?

class Bar extends Foo {
  // must set these values
  id = 1
  name = 'bar'
}


这个概念或模式有名称吗?我不能将Foo作为接口,因为它必须具有继承的类可以使用的方法。

最佳答案

Foo提供一个需要它们作为参数的构造函数:

class Foo {
  constructor(public id: number, public name: string) {
    // Validate them here if desired
  }

  sayHi() {
    console.log('hi');
  }
}


由于子类必须(隐式或显式)调用其超类构造函数,因此在不传递必要参数的情况下进行尝试的尝试将被TypeScript编译器标记:Supplied parameters do not match any signature of call target.例如,这两个均失败:

class Bar extends Foo {
}
const b = new Bar();   // Supplied parameters do not match any signature of call target.




class Bar extends Foo {
  constructor() {
    super();           // Supplied parameters do not match any signature of call target.
  }
}




请注意那里使用的有趣的TypeScript功能:因为我们在构造函数参数上提供了访问修饰符,所以实例属性将自动创建并在调用构造函数时设置为这些值。等效于:

class Foo {
  id: number;
  name: string;

  constructor(id: number, name: string) {
    this.id = id;
    this.name = name;
    // Validate them here if desired
  }

  sayHi() {
    console.log('hi');
  }
}


(由于默认修饰符为public。)

10-05 20:51
查看更多