【问题标题】:How to combine TypeScript constructor parameter properties with class inheritance and superclass constructor?如何将 TypeScript 构造函数参数属性与类继承和超类构造函数结合起来?
【发布时间】:2018-07-17 23:47:13
【问题描述】:

我知道,在 TypeScript 中,可以:

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

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

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

【问题讨论】:

    标签: typescript


    【解决方案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);
        }
    }
    

    【讨论】:

    • 感谢您的澄清!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 2012-09-03
    • 2018-06-06
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    相关资源
    最近更新 更多