Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Generic class<T> name of typescript?

Tags:

My Generic class

 export class BaseService<T> {  public subUrl;  constructor(public repo:RepogitoryService) { } } 

How can I store the class name of T on a local variable?

like image 997
Shahin Al Kabir Mitul Avatar asked Nov 15 '17 16:11

Shahin Al Kabir Mitul


2 Answers

You must understand that Typescript is just a transpiler (compiler to javascript). Some of the syntax sugar (such as generics) are working only in type-checking phase (and also it's helpful for intellisense in your IDE/text-editor).

However assignment to a variable is happening in runtime, in runtime it's just a plain Javascript. There are no types and no generics in runtime.

But here's the easiest way I would do it:

class Some<T> {     private TName : string;     constructor(x : T&Function) {         this.TName = x.name;     } }  class Another {  }  const some = new Some<Another>(Another); 
like image 63
durisvk10 Avatar answered Nov 08 '22 08:11

durisvk10


durisvk10 workaround covers the topic, just want to add that I would rather use
x: new () => T than x: T&Function.

Like this:

... constructor(x : new () => T) {     this.TName = x.name; }     ... 
like image 38
Yaremenko Andrii Avatar answered Nov 08 '22 08:11

Yaremenko Andrii