问题
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.
Here's an example:
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!
So. From this example i want to clone my bar instance, that should be instance of Child
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 :)
回答1:
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'
来源:https://stackoverflow.com/questions/34471231/create-new-instance-of-child-class-from-base-class-in-typescript