user3362334
user3362334

Reputation: 2180

Type 'Observable<unknown>' is not assignable to type 'Observable<ApiResponse>'

In an Angular project, I have a function defined in my service that is supposed to call my API.

This function looks like this:

apiCall(type: string, path: string, params: string[], data: any, headers?: HttpHeaders) {
let result = new Observable();
result = this.http.get(API_URL + '/' + path, {headers});

return result.pipe(
      tap(
        (response: ApiResponse) => {
          // console.log(response);
          return {...response};
        }),
      catchError(this.handleError())
    );
}

However, on this last line of code I get the following error:

TS2345: Argument of type 'MonoTypeOperatorFunction<ApiResponse>' is not assignable to parameter of type 'OperatorFunction<unknown, ApiResponse>'.   Types of parameters 'source' and 'source' are incompatible.     Type 'Observable<unknown>' is not assignable to type 'Observable<ApiResponse>'.       Type 'unknown' is not assignable to type 'ApiResponse'.

I tried to search for this error, but I haven't find a solution anywhere.

The weird thing is that this same code was working in other projects so I don't understand what's wrong

Upvotes: 0

Views: 495

Answers (1)

Guerric P
Guerric P

Reputation: 31805

By doing this:

let result = new Observable();
result = this.http.get(API_URL + '/' + path, {headers});

You are assigning a new Observable and then replacing it with another Observable from the Angular framework. Besides the fact that it's useless, TypeScript infers the type of result from its first assignment: Observable<unknown>.

So just write this instead:

const result = this.http.get<ApiResponse>(API_URL + '/' + path, { headers });

Upvotes: 5

Related Questions