[英]Is there a way to get the name of the generic type in a generic (<T>) function/class (Typescript)?
Here is the definition of my function: 这是我的函数的定义:
getData<T extends Entity> () { }
I don't currently accept any arguments. 我目前不接受任何论点。 Is there a way for me to translate the T into the string name of the type at runtime? 有没有办法让我在运行时将T转换为该类型的字符串名称? Perhaps using typeof? 也许使用typeof?
I am from the C# world where you would use reflection. 我来自C#世界,你会使用反射。 However I am new to Javascript and not sure what the equivalent would be. 但是,我是Javascript的新手,不知道等效的是什么。
Thanks. 谢谢。
Types are erased during compilation, so no. 类型在编译期间被删除,所以没有。 You should never ever have a generic function that doesn't use its type parameter in an argument position. 你不应该曾经有不中的参数位置使用其类型参数的通用函数。
Assuming getData
works on classes, you could write something like: 假设getData
适用于类,您可以编写如下内容:
class NotSureThisIsReallyAGoodIdea {
static getData<T>(cls: new(...args: any[]) => T): T {
/* magic happens */
const url = 'http://example.com/' + cls['name'];
return <T>undefined;
}
}
class SomeShape {
x: number;
}
let s = NotSureThisIsReallyAGoodIdea.getData(SomeShape);
s.x; // OK
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.