7

This piece of code transpiles with Babel and TypeScript and works as expected.

class ParentClass {
    static staticProp = true; 

    method() {
        console.log(this.constructor.staticProp);
    }
}

class ChildClass extends ParentClass {
    static staticProp = false;
}

(new ChildClass).method(); 

The requirement here is to refer to static property of current class (through this.constructor) instead of mentioning the class explicitly, so the method can be inherited and use the relevant static property in child classes.

It is ok for Babel, and TypeScript compiles it as well, but it throws

error TS2339: Property 'staticProp' does not exist on type 'Function'.

on compilation.

How can this case be treated to please TypeScript compiler?

3 Answers 3

10

TypeScript only supports ClassName.staticPropertyName syntax at the moment. There is, however, an open issue asking for simplifying it.

You can also wrap your staticProp in a getter. It's cumbersome but at least it does not feel like a language hack:

class ParentClass {
    static staticProp = true; 

    method() {
        console.log(this.staticProp);
    }

    get staticProp(): boolean { return ParentClass.staticProp; }
}

class ChildClass extends ParentClass {
    static staticProp = false; 

    get staticProp(): boolean { return ChildClass.staticProp; }
}

(new ChildClass).method(); 
Sign up to request clarification or add additional context in comments.

1 Comment

Well, the problem is that if you go with @pmcoltrane solution, you lose type information. You can do let p = this.constructor["staticProp"] as boolean but this way you specify the type twice and if you do some refactoring, you may get an error. So there are pros and cons. It would be great to have self keyword but unfortunately it is not supported. This is also the reason why I would use the getters (even though they are clumsy), because my IDE could control my code and a chance of introducing a bug would be lower.
7

I was able to make TypeScript keep silent with

class ParentClass {
    static staticProp = true; 

    method() {
        console.log((<typeof ParentClass>this.constructor).staticProp);
    }
}

Comments

4

If you are willing to sacrifice type checking, you can get rid of the TypeScript compiler error by indexing the property:

console.log(this.constructor["staticProp"]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.