Typescript access to the static attribute of a generic type

I have an abstract Model class with a static attribute and another common Controller<T extends Model> class. I want to access the static attribute of Model in an instance of Controller. This should like:

 abstract class Model{ static hasStatus: boolean = false; } class MyModel extends Model{ static hasStatus = true; } class Controller<T extends Model>{ constructor(){ if(T.hasStatus)... } } 

But TS says 'T' only refers to a type, but is being used as a value here.

Is there an easy way to achieve this? Or should I subclass Controller for each Model legacy and implement a method to extract the value?

+5
source share
1 answer

There is no way in typescript to do this. Type type parameters can only be displayed where types can be displayed in declarations; they are not available at run time. The reason for this is simple: for each method of a universal class, a single javascript function is created, and there is no way for this function to find out what actual type was passed as a parameter of the type type.

If you need this information at runtime, you need to add a parameter to the constructor and pass it yourself when called:

 class Controller<T extends Model>{ constructor(cls: typeof Model){ if (cls.hasStatus) { } } } let c = new Controller<MyModel>(MyModel); 

Here's what it looks like when compiling in javascript to illustrate this point: there is nothing left of the general parameters, and if you remove the cls parameter, there is no information about where hasStatus should appear.

 var Controller = (function () { function Controller(cls) { if (cls.hasStatus) { } } return Controller; }()); var c = new Controller(MyModel); 
+3
source

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


All Articles