如何获取传递的泛型参数的类名
class Sample<T>{
public getTypeName(): void {
alert(T.name)
//or
alert(new T().constructor.name)
}
}
class Person {
public FullName:string
}
new Sample<Person>().getTypeName()
我需要将输出打印为“Person”?
最佳答案
虽然类型泛型类型在编译时被清除,但您可以传入类的构造函数并获取其名称:
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()
关于typescript - 获取传递给 typescript 的泛型参数的类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51906554/