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 :)

  • If anyone is still encountering this and looking for a solution that does not discard type information, the strategy posted here (https://stackoverflow.com/a/45871004/131782) about returning `this` seems to work. – Breck Oct 12 '20 at 23:05

1 Answers1

6

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'
Gerrit Bertier
  • 4,101
  • 2
  • 20
  • 36
  • Is it not possible to say that this.constructor derives from Base? – Colin D Oct 04 '19 at 21:55
  • 1
    Doing it this way you lose Type information. The correct solution likely involves generics, though I haven't quite figured it out. – Breck Oct 12 '20 at 22:54