Sushant Yadav Sushant Yadav - 2 months ago 19
TypeScript Question

Return a new instance of Child class from base class static method

What I am stuck at:

I want a Base class which can return a new object of its child class.

like:

export class Base {
constructor () {
}

static query() {
//return a new object of class from which this function is called.
}

}

export class Child extends Base {

}


now in my IndexComponent Class

export class IndexComponent {
var user = Child.query() // By this I have a new object of Child class in user variable
}


Thank you in advance!

Answer

The solution is simple:

export class Base {
    constructor () {}

    static query() {
        return new this();
    }
}

let base = Base.query(); // Base {}
let child = Child.query(); // Child {}

(code in playground)

This works because when executing a static function then the this is the constructor function.
You can see that in the compiled js:

var Base = (function () {
    function Base() {
    }
    Base.query = function () {
        return new this();
    };
    return Base;
}());

The query function is a property of Base constructor function, and will also be a property of Child because it extends Base.

The problem here is how to type this query function so that the compiler will know what is the returned type.
For now you'll need to do this:

let base = Base.query(); // here base is of type 'Base'
let child: Child = Child.query(); // need to declare the type
// or
let child2 = Child.query() as Child; // or assert it

I can't think of a way to make the compiler infer the right type which is returned, would love to know if anyone has an idea.