user2146414
user2146414

Reputation: 1038

Rxjs catchError casuses TypeScript type error

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.

Upvotes: 0

Views: 618

Answers (1)

Mike Jerred
Mike Jerred

Reputation: 10565

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}))

Upvotes: 1

Related Questions