我想从基类方法创建子类的新实例。
这有点复杂,但我会尽力解释。
这是一个例子:
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:)