Angular presents an interesting case scenario. In this example, there are two interfaces: one defines the variable status
as a string, while the other enumerates specific values that status
can hold. The issue arises with the latter interface because the catchError
function fails to return the appropriate 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"}))
);
}
}
An error message like
TS2322 Type Observable<ThisInterfaceCausesProblem|{status: string}> is not assignable to type Observable<ThisInterfaceCausesProblem>
keeps popping up, but the reason behind it remains elusive.