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?
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);
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; } ...
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