从Typescript中的Base类创建Child类的新实例 [英] Create new instance of Child class from Base class in Typescript
问题描述
我想通过 Base 类方法创建 Child 类的新实例.
I want to create new instance of Child class from Base class method.
这有点复杂,但是我会尽力解释.
It's a little bit complicated, but i will try to explain.
这是一个例子:
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!
所以.从这个示例中,我想克隆我的bar
实例,该实例应该是Child
So. From this example i want to clone my bar
instance, that should be instance of Child
好吧.我正在尝试在Bar.clone
方法中进行跟踪:
Well. I'm trying following in Bar.clone
method:
clone(){
return new this.constructor()
}
...而且这在已编译的代码中有效,但是我遇到打字稿错误:
...And this works in compiled code, but i have typescript error:
error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.
有什么办法可以解决这个问题吗?
Any ideas how i can handle this?
谢谢.希望这对某人有帮助:)
Thank you. Hope this helps some1 :)
推荐答案
克隆未知对象时,您需要转换为通用对象.
最好的方法是使用<any>
语句.
You need to cast to a generic object when cloning an unknown object.
The best way to do this is to use the <any>
statement.
class Base {
constructor() {
}
public clone() {
return new (<any>this.constructor);
}
}
class Child extends Base {
test:string;
constructor() {
this.test = 'test string';
super();
}
}
var bar = new Child();
var cloned = bar.clone();
console.log(cloned instanceof Child); // returns 'true'
console.log(cloned.test); // returns 'test string'
这篇关于从Typescript中的Base类创建Child类的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!