Oddleif
Oddleif

Reputation: 801

error TS2322: Type 'Observable<{} | T>' is not assignable to type 'Observable<T>'

I found this examlpe for async pipe error handling for Angular which looked promising: https://sebastian-holstein.de/post/error-handling-angular-async-pipe/

Trying to run it in angular 7 though causes compilation errors

readonly data$: Observable<T>;

  constructor(data: Observable<T>) {
    this.data$ = data.pipe(
      shareReplay(1),
      catchError(error => {
        console.log(error);
        this._errorLoading$.next(true);
        return of();
      })
    );
  }

Error:

ERROR in src/app/loading-wrapper.ts(12,5): error TS2322: Type 'Observable<{} | T>' is not assignable to type 'Observable<T>'.
  Type '{} | T' is not assignable to type 'T'.
    Type '{}' is not assignable to type 'T'.

Full class

enter image description here

Any suggestions on how to fix?

Upvotes: 2

Views: 799

Answers (2)

user184994
user184994

Reputation: 18281

It's because you do return of();, and the value being passed to of is not of type T.

You can instead do return of(null);, or ensure you pass a value of type T to the of function.

Upvotes: 7

MrAleister
MrAleister

Reputation: 1581

Try this declaration:

readonly data$: Observable<{} | T>;

Upvotes: 1

Related Questions