【问题标题】:Is it possible to get the type name of a generic type?是否可以获得泛型类型的类型名称?
【发布时间】:2017-04-30 20:25:27
【问题描述】:

我有一个execute<TResult>(): Observable<TResult> 的方法签名

如何获取 TResult 类型的名称?

示例:

execute<ViewModel> --> "ViewModel" 是我需要的结果。

【问题讨论】:

    标签: generics typescript reflection typescript2.0 typename


    【解决方案1】:

    据我所知,无法获取TResult 的名称,但如果您提供相应的构造函数,则可以获取名称。

    声明:

    execute<TResult>(ctor: { new (): TResult }) : <TResult> {
      console.log(ctor.name) //Prints out SomeClass
      return <any>null;
    }
    

    用法:

    execute<SomeClass>(SomeClass);
    

    【讨论】:

    • 谢谢!我不太确定那里会发生什么。您能否详细说明 new(): TResult 部分?我的第一个猜测是,这会创建一个匿名构造函数类,将其属性添加到我们通过 ctor 参数访问的新对象中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多