相关疑难解决方法(0)

在 Typescript 中从基类创建 Child 类的新实例

我想从基类方法创建类的新实例。

这有点复杂,但我会尽力解释。

这是一个例子:

class Base(){
    constructor(){}

    clone(){
        //Here i want to create new instance
    }
}

class Child extends Base(){}


var bar = new Child();
var cloned = bar.clone();

clone instanceof Child //should be true!
Run Code Online (Sandbox Code Playgroud)

所以。从这个例子中我想克隆我的bar实例,那应该是实例Child

出色地。我正在尝试以下Bar.clone方法:

clone(){
    return new this.constructor()
}
Run Code Online (Sandbox Code Playgroud)

...这在编译代码中有效,但我有打字稿错误:

error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

我有什么想法可以处理这个问题吗?

谢谢。希望这对一些人有帮助1:)

javascript oop inheritance typescript

4
推荐指数
1
解决办法
8244
查看次数

标签 统计

inheritance ×1

javascript ×1

oop ×1

typescript ×1