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

问题描述 投票:0回答:1

据我所知,在TypeScript中,人们可以:

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

这有点令人困惑,我无法从文档中弄清楚这是否可行,或者 - 如果是 - 如何。

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

typescript
1个回答
1
投票

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

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.