Using a static property in an inherited class method

This piece of code translates from 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 reference the static property of the current class (via this.constructor ) instead of explicitly specifying the class, so you can inherit the method and use the corresponding static property in the child classes.

This is normal for Babylon, and TypeScript compiles it too, but it throws

error TS2339: property 'staticProp' does not exist in type 'Function'.

when compiling.

How can I handle this case to TypeScript?

+5
source share
3 answers

I managed TypeScript to be silent with

 class ParentClass { static staticProp = true; method() { console.log((<typeof ParentClass>this.constructor).staticProp); } } 
+4
source

TypeScript only supports the syntax ClassName.staticPropertyName . There is, however, an open question asking to simplify it.

You can also wrap staticProp in a getter. This is cumbersome, but at least it doesn't look like hacking a language:

 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(); 
+8
source

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

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

Source: https://habr.com/ru/post/1239379/


All Articles