【问题标题】:Is there a way to get the name of the generic type in a generic (<T>) function/class (Typescript)?有没有办法在泛型 (<T>) 函数/类 (Typescript) 中获取泛型类型的名称?
【发布时间】:2016-04-11 19:56:36
【问题描述】:

这是我的函数的定义:

getData<T extends Entity> () { }

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

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

谢谢。

【问题讨论】:

  • 如果没有参数那你为什么需要那个类型呢?
  • 我需要编写一个 url 字符串,其中一部分是类 T 的名称。我将返回一个泛型类型的对象:例如,Result。
  • 也许覆盖toString() 方法会有所帮助?

标签: javascript generics typescript


【解决方案1】:

类型在编译期间被删除,所以不会。您应该永远 永远有一个不在参数位置使用其类型参数的泛型函数。

假设 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

【讨论】:

  • 这对我有用,谢谢。 getData(type: { new(): T ;} ) { let d = new type();让名称:字符串 = d.getName(); }(不确定如何格式化代码示例)
猜你喜欢
  • 2020-08-28
  • 2020-11-15
  • 2022-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-06
  • 2019-05-30
相关资源
最近更新 更多