4

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
  • If anyone is still encountering this and looking for a solution that does not discard type information, the strategy posted here (stackoverflow.com/a/45871004/131782) about returning this seems to work. Commented Oct 12, 2020 at 23:05

1 Answer 1

7

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'
Sign up to request clarification or add additional context in comments.

2 Comments

Is it not possible to say that this.constructor derives from Base?
Doing it this way you lose Type information. The correct solution likely involves generics, though I haven't quite figured it out.