代码之家  ›  专栏  ›  技术社区  ›  RajeshKdev

如何在typescript中获取泛型方法内的t类型?

  •  5
  • RajeshKdev  · 技术社区  · 7 年前

    我在一个类中有一个泛型方法。

    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 在那个方法里面。

    我该怎么做?

    1 回复  |  直到 7 年前
        1
  •  6
  •   John Weisz    7 年前

    可以访问类装饰器中类的构造函数引用、属性(或访问器)装饰器中的属性或参数装饰器中的参数(使用 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

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