2

请看下面的评论:

class MyClassA {
    constructor(optionalParam?: any) {
    }

    initialize(optionalParam?: any) {
    }   
}

class MyClassB extends MyClassA {
    constructor(requiredParam: any) {
        super(requiredParam);
        // OK.
    }

    // I want to override this method and make the param required
    // I can add the private modifier but I want it to
    // be public and hide the method with optionalParam
    initialize(requiredParam: any) {
        // compiler error!
    }
}

我怎样才能做到这一点?

谢谢!

4

1 回答 1

2

编译器正在阻止您违反继承合同 - 建议MyClassB不能用作MyClassA.

考虑:

var x = new MyClassB(); // Create a new MyClassB
var y: MyClassA = x;    // OK
y.initialize();         // OK... but MyClassB isn't going to get a value for requiredParam

您可以重构,使其MyClassB不派生自MyClassA,或任何数量的其他选项。

于 2013-01-30T23:53:16.223 回答