Create new instance of Child class from Base class in Typescript [duplicate]

久未见 提交于 2019-12-24 17:31:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!