Create new instance of Child class from Base class

2019-08-12 16:33发布

This question already has an answer here:

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条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-12 17:17

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'
查看更多
登录 后发表回答