我有一個基本的服務和模型來獲取一些看起來像這樣的資料:
//api.model.ts
interface ApiErrorResponse {
hasError: boolean;
error?: {
code: number;
errorDomain: string;
description: string;
field: string;
};
}
interface ApiGetResponse<T> extends ApiErrorResponse {
response?: {
items?: T[];
};
}
//some.service.ts
import ...
interface Item {
name: string;
value: number;
}
type ItemApiResponse = ApiGetResponse<Item>;
class SomeUnNamedService {
constructor(private http: HttpClient) {
public getSomeData( userId: number): Observable<ItemApiResponse> {
this._loadingSubject.next(true);
this._errorSubject.next(false);
return this.http.post<ItemApiResponse>(
`${environment._API_}/Some/Api/EndPoint`,
{
userId
}
).pipe(
map( res => {
if(res.response?.items?.length === 0) {
this._emptySubject.next(true);
}
return res;
}),
catchError((err: ApiErrorResponse) => {
this._errorSubject.next(true);
return throwError(err);
}),
finalize(() => this._loadingSubject.next(false))
);
}
上面的代碼有效,一切都很好。但是我的計劃是讓這個管道(?)運算子(?)可重用,因為我要在多個服務中使用它。所以我在https://stackoverflow.com/a/50908353/1501643 的幫助下創建了這個
function responseObserver<T>(thisArg) {
return pipe(
map((res: T) => {
// Property 'response' does not exist on type 'T'.
console.log(res?.response);
thisArg._emptySubject.next(true);
return res;
}),
catchError((err: ApiErrorResponse) => {
thisArg._errorSubject.next(true);
return throwError(err);
}),
finalize(() => thisArg._loadingSubject.next(false))
);
}
// I invoke it like this:
public getSomeData(
userId: string,
): Observable<ItemApiResponse> {
.....
return this.http
.post<ItemApiResponse>(
`${environment._API_}/Some/Api/Endpoint`,
{
userId
}
)
.pipe(responseObserver<ItemApiResponse>(this));
}
但是,正如您所看到的,TS 編譯器抱怨“回應”沒有退出……我在這里錯過了什么?為什么編譯器不能解釋泛型型別?我使用的是 TypeScript 3.8
uj5u.com熱心網友回復:
您假設泛型型別將包含一個response屬性,但您尚未定義任何規則來讓編譯器做出該假設。在您的函式上添加這樣的規則 -
function responseObserver<T extends ApiGetResponse <T>>(thisArg)- 應該允許您從泛型型別訪問回應屬性而不會出現編譯器錯誤,因為它讓編譯器知道您的泛型型別將具有 ApiGetResponse 物件的屬性,該物件確實具有回應屬性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/372518.html
上一篇:使用正則運算式洗掉部分字串并替換
下一篇:型別覆寫類內的型別
