有没有一种方法可以在泛型(<T>)函数/类(Typescript)中获取泛型类型的名称

Is there a way to get the name of the generic type in a generic (<T>) function/class (Typescript)?

本文关键字:函数 Typescript 获取 泛型类型 gt lt 方法 一种 有没有 泛型      更新时间:2024-04-25

以下是我的函数的定义:

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