Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何使用可选参数覆盖/隐藏方法?_Typescript - Fatal编程技术网

Typescript 如何使用可选参数覆盖/隐藏方法?

Typescript 如何使用可选参数覆盖/隐藏方法?,typescript,Typescript,请参阅以下评论: class MyClassA { constructor(optionalParam?: any) { } initialize(optionalParam?: any) { } } class MyClassB extends MyClassA { constructor(requiredParam: any) { super(requiredParam); // OK. }

请参阅以下评论:

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
,或任何其他选项。

还发布了一个问题。您是对的。我检查过了,相反的情况是可能的。例如,在父对象上有一个带有必需参数的方法,然后在子对象上用可选参数将其重写为方法。谢谢