[英]Rxjs catchError casuses TypeScript type error
我有一個來自 Angular 的例子。 有兩個接口。 一個將status
定義為字符串。 第二個定義status
值。 問題出在后一個,因為catchError
function 沒有返回正確的類型:
export interface ThisInterfaceIsOk {
status: string;
}
export interface ThisInterfaceCausesProblem {
status: "OK" | "PROBLEM";
}
@Injectable({
providedIn: 'root'
})
export class RegisterService {
constructor(private httpClient: HttpClient) {
}
public registerValid(): Observable<ThisInterfaceIsOk> {
return this.httpClient.get('http://example.com/api').pipe(
map(response => response as ThisInterfaceIsOk),
catchError(() => of({status: "WHATEVER"}))
);
}
public registerInvalid(): Observable<ThisInterfaceCausesProblem> {
return this.httpClient.get('http://example.com/api').pipe(
map(respone => respone as ThisInterfaceCausesProblem),
catchError(() => of({status: "OK"}))
);
}
}
錯誤就像TS2322 Type Observable<ThisInterfaceCausesProblem|{status: string}> is not assignable to type Observable<ThisInterfaceCausesProblem>
但我真的不明白為什么。
我相信catchError(() => of({status: "OK"}))
給出的返回類型為{ status: string }
。 嘗試用這個替換它: catchError(() => of({status: "OK" as const}))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.