繁体   English   中英

如何在Typescript中的泛型方法中获取T的类型?

[英]How to get the type of T inside generic method in Typescript?

我在一个类中有一个通用方法。,

export class BaseService {
    public getAll<T>(): Observable<T> {
        // get type of T

        // const type = typeof(T); // Tried this but getting compilation exceptions 

        return this.http.get<T>(this.actionUrl + 'getAll');
    }
}

我将从其他几个打字稿类中调用如下所示的方法。

this.service.getAll<SubscriberData>().subscribe(response => {
      // Response
    }, error => {
      console.log(error);
    }, () => {
      // do something commonly
    });

当我尝试此操作时出现以下异常

const type = typeof(T); 

'T' 仅指一种类型,但在此处用作值。

编辑:

我正在尝试获取调用泛型方法的类的类型。 例如: getAll<SubscriberData>我想在该方法中获取类型SubscriberData

我怎样才能做到这一点?

您可以访问类装饰器中类的构造函数引用、属性(或访问器)装饰器中的属性或参数装饰器中的参数(使用反射元数据)。

不幸的是,泛型类型参数在运行时无法以这种方式使用,它们将始终产生与简单Object类型等效的运行时。

相反,您可以提供构造函数引用,您也可以使用它来推断泛型类型(即,不是指定泛型类型,而是指定该泛型类型的相应构造函数引用):

export class BaseService {
    public getAll<T>(TCtor: new (...args: any[]) => T): Observable<T> {
        // get type of T
        const type = typeof(TCtor);

        // ...
    }
}

然后像这样使用它:

new BaseService().getAll(DataClass); // instead of 'getAll<DataClass>()'

操场上的演示

类型new (...args: any[]) => T简单地说:一个 newable 类型(即类/构造函数),它返回泛型T类型(换句话说,泛型T实例的相应类/构造函数)类型)。

非常感谢! 这是我在网上找到的唯一选项。 我不知道他们为什么不能在某些通用库中实现此功能

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM