我在课堂上有一个通用方法.,
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>()'
新类型(… args:any [])=> T简单地说:一个返回通用T类型的新类型(即类/构造函数)(换句话说,通用T实例类型的相应类/构造函数).