[英]Get class name of generic parameter passed typescript
How do i get the class name of the generic parameter passed我如何获取传递的泛型参数的类名
class Sample<T>{
public getTypeName(): void {
alert(T.name)
//or
alert(new T().constructor.name)
}
}
class Person {
public FullName:string
}
new Sample<Person>().getTypeName()
I need the output to be printed as " Person " ?我需要将输出打印为“人”?
While type generic types are erased at compiler time, you can pass in the constructor of the class and get the name of that:虽然在编译器时擦除了泛型类型,但您可以传入类的构造函数并获取其名称:
class Sample<T>{
public constructor(public tCtor: new (...args:any[]) => T){}
public getTypeName(): void {
console.log(this.tCtor.name)
}
}
class Person {
public FullName!:string
}
new Sample(Person).getTypeName()
Because I cannot comment to the answer of Titian Cernicova-Dragomir :因为我无法评论Titian Cernicova-Dragomir的回答:
This only makes sense, if the context of the caller is non-generic, which might often not be the case.这只有在调用者的上下文是非通用的情况下才有意义,但通常情况并非如此。 If I only have a generic parameter at hand (for example in a generic class), there is no way to create a runtime instance of it's instanciated type or use the name of the instanciated type, even if the needed information should be available at compile time.如果我手头只有一个泛型参数(例如在泛型类中),则无法创建它的实例化类型的运行时实例或使用实例化类型的名称,即使所需的信息应该在编译时可用时间。 It's a pity for people which are used to C++ Templates or Java/C# Generics.对于习惯了 C++ 模板或 Java/C# 泛型的人来说,这是一种遗憾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.