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?
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;
}
...
You cannot, unfortunately. Typescript is a static type checker and has no support for type reflection at runetime such as java does. This is because its sources are transpiled to javascript.
However, there is hope for such support in the future, with a new typescript feature called "custom transformers". Those transformers are plugins that hook the transpilation process, opening the road to rich features regarding type reflection. A first example of such is ts-transformer-keys
.
Cast the object to Object
and get constructor name?
function nameOf(object: Object): string {
return object.constructor.name;
}
Typescript removes all type information in the emitted Javascript (and thus at runtime), but thanks to Typescript's "transformers" feature, it is now possible to write a transformer to expose this information at runtime. I have done just that, see https://typescript-rtti.org/ - No decorators required, and it is far more comprehensive than emitDecoratorMetadata