Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access child class' static members from base class

Tags:

typescript

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?

like image 993
David Sherret Avatar asked Dec 31 '13 03:12

David Sherret


1 Answers

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
    }
}
like image 163
David Sherret Avatar answered Sep 27 '22 00:09

David Sherret