问题描述
这是我的功能的定义:
getData<T extends Entity> () { }
我目前不接受任何论点.我有办法在运行时将T转换为类型的字符串名称吗?也许使用typeof?
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? Perhaps using typeof?
我来自C#世界,您将在其中使用反射.但是,我是Java语言的新手,不知道这会是什么.
I am from the C# world where you would use reflection. However I am new to Javascript and not sure what the equivalent would be.
谢谢.
推荐答案
编译期间会删除类型,因此不会.您应该从不 从 具有一个通用函数,该函数在参数位置不使用其类型参数.
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.
假设getData
适用于类,您可以编写类似以下内容的
Assuming getData
works on classes, you could write something like:
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
这篇关于有没有办法在通用(< T>)函数/类(Typescript)中获得通用类型的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!