[英]Is there a way to get the name of the generic type in a generic (<T>) function/class (Typescript)?
这是我的函数的定义:
getData<T extends Entity> () { }
我目前不接受任何论点。 有没有办法让我在运行时将T转换为该类型的字符串名称? 也许使用typeof?
我来自C#世界,你会使用反射。 但是,我是Javascript的新手,不知道等效的是什么。
谢谢。
类型在编译期间被删除,所以没有。 你不应该曾经有不中的参数位置使用其类型参数的通用函数。
假设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.