Andrei Tarutin
Andrei Tarutin

Reputation: 683

How to invoke static method of type parameter in TypeScript

Is it possible to call static method of type parameter? For example, I have the following code:

class BaseA1 {
  public static getString(): string {
    return "A1";
  }
}

class A<A1 extends BaseA1> {
  constructor() {
    var name = A1.getString(); // <== error [the property getString does not exist ...]
  }
}

How to call static method correctly? Is it possible at all, if not what might be the best alternative way? Thanks, kindly.

Upvotes: 2

Views: 2330

Answers (1)

Ingo B&#252;rk
Ingo B&#252;rk

Reputation: 20063

Static methods belong to the class type, not to an instance. In particular, if A1 defined it's own getString, it would not be an overridden method, but a shadowed method.

So the only scenario in which what you want to do makes sense is when you want to rely on a type shadowing a method from its base type. This, however, would be very smelly code (in other words: don't do it).

Either call BaseA1.getString() or, if you need a way to override it in a subclass, have it be a proper instance method. Seeing that your example returns the name of the subclass, I tend to think you are trying to achieve something fishy and would suggest you ask another question on what the underlying problem is that you want to solve rather than asking a question on how to make the current design work.

You can find an explanation on this here; it's about Java rather than Typescript, but the idea is the same.

Upvotes: 2

Related Questions