typescript - 如何覆盖/隐藏带有可选参数的方法?

标签 typescript

请参阅下面的评论:

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/

相关文章:

typescript - 如何在TS编译错误时使webpack2失败?

Angular 10/ typescript : What is the difference between how the same property of an object is being assigned

typescript - 类型 'downloadURL' 上不存在属性 'AngularFireUploadTask'

javascript - 无法在 p-autocomplete 中将值绑定(bind)到 ngModel

javascript - 在 IONIC2 中获取动态创建的 ionic 输入值

javascript - Next.js v12 中间件不适用于 node-fetch 和 axios

html - Angular 4 在 *ngFor 内调用函数时卡住

angular - 如何在 Angular 中动态添加额外的路由

javascript - 在 Angular 中,如何在构建后手动编辑环境变量?

typescript - 方法重载不适用于 Typescript