有没有办法在泛型(<T>)函数/类(Typescript)中获取泛型类型的名称?

Ane*_*ter 5 javascript generics typescript

这是我的函数的定义:

getData<T extends Entity> () { }
Run Code Online (Sandbox Code Playgroud)

我目前不接受任何论点.有没有办法让我在运行时将T转换为该类型的字符串名称?也许使用typeof?

我来自C#世界,你会使用反射.但是,我是Javascript的新手,不知道等效的是什么.

谢谢.

Rya*_*ugh 5

类型在编译期间被擦除,所以没有。你应该永远 永远都不会在争吵位置使用其类型参数的通用函数。

假设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
Run Code Online (Sandbox Code Playgroud)