I have an example from Angular. There are two interfaces. One defines status
as string. The second one defines status
values. The problem is the later one because the catchError
function does not return proper type for it:
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"}))
);
}
}
The error is like TS2322 Type Observable<ThisInterfaceCausesProblem|{status: string}> is not assignable to type Observable<ThisInterfaceCausesProblem>
but I really do not understand why.
I believe the line catchError(() => of({status: "OK"}))
gives a return type of { status: string }
. Try replacing it with this: catchError(() => of({status: "OK" as const}))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.