Skip to content Skip to sidebar Skip to footer

Create New Instance Of Child Class From Base Class In Typescript

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(){}

Solution 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'

Post a Comment for "Create New Instance Of Child Class From Base Class In Typescript"