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?
Static methods in Java are inherited, but can not be overridden. If you declare the same method in a subclass, you hide the superclass method instead of overriding it. Static methods are not polymorphic. At the compile time, the static method will be statically linked.
Static methods take all the data from parameters and compute something from those parameters, with no reference to variables. We can inherit static methods in Java.
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object.
The static properties and methods of a class are created using the static keyword.
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();
I was able to make TypeScript keep silent with
class ParentClass {
static staticProp = true;
method() {
console.log((<typeof ParentClass>this.constructor).staticProp);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With