coderman
coderman

Reputation: 1514

rxjs - [ts] Type 'Observable<{} | T>' is not assignable to type 'Observable<T>'

    public get<T>(url: string, httpParams: Array<Map<string, string>>): Observable<T> {
    return this.httpClient
        .get<T>(url, { params: this.appendHttpParams(httpParams), headers: this.httpHeaders })
        .catch((error, some): any => {
            console.log(error);
        });

}

I have this wrapper function around my http service in Angular 4. It works fine without the return type specified. However, if I provide the same return type of the 'httpClient.get()' which is Observable, it throws an error

[ts] Type 'Observable<{} | T>' is not assignable to type 'Observable'. Type '{} | T' is not assignable to type 'T'. Type '{}' is not assignable to type 'T'.

What am I missing?

Upvotes: 0

Views: 207

Answers (1)

Pace
Pace

Reputation: 43867

You probably want to use do and not catch. catch is intended for scenarios where you want to handle the error and continue the observable chain. In a catch method you are supposed to return a different observable that the chain can switch to. For example:

this.httpClient
    .get<T>(...)
    .catch(err => {
        return this.cachedVersion;
    );

Anyways, since you don't have any return statement in your catch method it is returning void. That is why your observable changes to Observable<T|{}> because it will be a chain that emits T if there is no error and {} if there is an error.

Upvotes: 1

Related Questions