Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using static property in inherited class method

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?

like image 226
Estus Flask Avatar asked Dec 28 '15 23:12

Estus Flask


People also ask

Can we use static method in inheritance?

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.

Can we inherit static class in Java?

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.

Does static method gets inherited in C#?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object.

Which keyword's are required to create a static property within a class?

The static properties and methods of a class are created using the static keyword.


2 Answers

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(); 
like image 53
Martin Vseticka Avatar answered Oct 06 '22 07:10

Martin Vseticka


I was able to make TypeScript keep silent with

class ParentClass {
    static staticProp = true; 

    method() {
        console.log((<typeof ParentClass>this.constructor).staticProp);
    }
}
like image 45
Estus Flask Avatar answered Oct 06 '22 06:10

Estus Flask