[英]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.