Create a new instance of the Child class from the base class in Typescript

I want to create a new instance of the Child class from the Base class .

This is a bit complicated, but I will try to explain.

Here is 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. In this example, I want to clone my instance bar, which must be an instanceChild

Well. I am trying to follow in a method Bar.clone:

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. Hope this helps some1 :)

+1
source share
1 answer

.
- <any>.

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'
+2

Source: https://habr.com/ru/post/1684413/


All Articles