请参阅下面的评论:
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!
}
}
我该怎么做?
谢谢!
最佳答案
编译器正在阻止您违反继承契约——建议的 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
或任意数量的其他选项派生。
关于typescript - 如何覆盖/隐藏带有可选参数的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14615873/