Raj*_*dev 5 generics typescript angular
我在一个类中有一个通用方法。
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');
}
}
Run Code Online (Sandbox Code Playgroud)
我将从其他一些打字稿类中调用如下所示的方法。
this.service.getAll<SubscriberData>().subscribe(response => {
// Response
}, error => {
console.log(error);
}, () => {
// do something commonly
});
Run Code Online (Sandbox Code Playgroud)
当我尝试此操作时出现以下异常
const type = typeof(T);
Run Code Online (Sandbox Code Playgroud)
“ T”仅指类型,在此被用作值。
编辑:
我试图获取正在调用通用方法的类的类型。例如: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);
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
new BaseService().getAll(DataClass); // instead of 'getAll<DataClass>()'
Run Code Online (Sandbox Code Playgroud)
类型new (...args: any[]) => T简单地说:一个可返回新类型(即类/构造函数),该T类型返回泛型类型(换句话说,泛型T实例类型的对应类/构造函数)。
| 归档时间: |
|
| 查看次数: |
2778 次 |
| 最近记录: |