如何将TypeScript构造函数参数属性与类继承和超类构造函数相结合



我知道,在TypeScript中,可以:

  • 使用参数属性从构造函数声明中声明类属性
  • 从基类继承,在这种情况下,派生类构造函数必须调用基类构造函数

有可能将这两种行为结合起来吗?也就是说,是否可以声明一个使用参数属性的基类,然后在一个也使用参数特性的派生类中从中继承?派生类是否需要重新声明它们,将它们传递到超类构造函数调用中,等等。?

这有点令人困惑,我无法从文档中弄清楚这是否是可能的,或者——如果是——如何实现。

如果有人对此有任何见解,请提前感谢。

您可以将两者结合,但从继承类的角度来看,声明为构造函数参数的字段将是常规字段和构造函数参数:

class Base {
constructor(public field: string) { // base class declares the field in constructor arguments
}
}
class Derived extends Base{
constructor(public newField: string, // derived class can add fields
field: string // no need to redeclare the base field
) {
super(field); // we pass it to super as we would any other parameter
}
}

注意

您可以在构造函数参数中重新声明字段,但它必须遵守重新声明字段的规则(兼容类型和可见性修饰符(

所以这是有效的:

class Base {
constructor(public field: string) {
}
}
class Derived extends Base{
constructor(public field: string) { //Works, same modifier, same type, no harm from redeclration
super(field);
}
}

但这不会奏效:

class Base {
// private field
constructor(private field: string) {
}
}
class Derived extends Base{
constructor(private field: string) { //We can't redeclare a provate field
super(field);
}
}

最新更新