加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:30:09 所属栏目:安全 来源:网络整理
导读:我在课堂上有一个通用方法., export class BaseService { public getAllT(): ObservableT { // get type of T // const type = typeof(T); // Tried this but getting compilation exceptions return this.http.getT(this.actionUrl + 'getAll'); }} 我将从
我在课堂上有一个通用方法.,

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’ only refers to a type,but is being used as a value here.

编辑:

我正在尝试获取调用泛型方法的类的类型.对于Ex:getAll< SubscriberData>我想在该方法中获取类型SubscriberData.

我怎样才能做到这一点?

解决方法

您可以在类装饰器中访问类的构造函数引用,在属性(或访问器)装饰器中访问属性,或者在参数装饰器中访问参数(使用 reflect-metadata).

遗憾的是,泛型类型参数在运行时不可用,它们总是会产生与简单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>()'

Demo on playground

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读