David Sherret David Sherret - 9 months ago 25
TypeScript Question

Access child class' static members from base class

I have the following base class:

class BaseClass {
public static myFlag: boolean = false;

constructor() {
//reference ChildClass.myFlag??
}
}


With the child class:

class ChildClass extends BaseClass {
constructor() { super(); }
}


And the following code:

ChildClass.myFlag = true;
var child = new ChildClass();


How can I reference the value of the child class'
myFlag
property without passing the child class to the base class' constructor?

Answer Source

The context of the constructor is the child object. To access the child class' static properties, use Object.prototype.constructor:

class BaseClass {
    public static myFlag: boolean = false;

    constructor() {
        console.log(this["constructor"].myFlag); // true
    }
}

Update

In newer versions of TypeScript you might need to do this for it to compile:

class BaseClass {
    public static myFlag: boolean = false;

    constructor() {
        const ctor = this.constructor as typeof BaseClass;
        console.log(ctor.myFlag); // true
    }
}