I have a similar case to one described in this post.
I have a user login service, which (among other things) verifies if user's token is still valid. The server's response is defined in an interface:
export interface UserVerifyResponse {
success: boolean
}
My aim was to create an observable that will return a boolean value depending on whether user is verified. This code was working with RxJS v6.2:
authenticate(): Observable<boolean> {
return this.http.get<boolean>(
this.apiUrl+'/verify_user'
).pipe(
map<UserVerifyResponse, boolean>((receivedData: UserVerifyResponse) => {
return receivedData.success;
}),
tap((data: boolean) => {console.log("User authenticated", data)}),
catchError(this.handleError)
)
}
However, now that I have updated RxJS to v6.3 I get this error:
ERROR in src/app/login/user.service.ts(50,13): error TS2345: Argument of type 'OperatorFunction<UserVerifyResponse, boolean>' is not assignable to parameter of type 'OperatorFunction<boolean, boolean>'.
Type 'UserVerifyResponse' is not assignable to type 'boolean'.
It bothers me, because I use this approach of mapping API response to an internal class or a primitive (in other place I have a service which uses http.get<T>
) and now I wonder if I should force RxJS 6.2 or there is an easy way to migrate to 6.3. I can rewrite all of them as it is described in the answer to the above mentioned post, but I I want to return a boolean value and my approach looks clearer in my opinion.
Any suggestions?
Apparently, they have improved the type-checking.
When you wrote this.http.get<boolean>
, you are saying "this get is returning an Observable of type boolean", which is not what you mean. The get is returning an Observable of type UserVerifyResponse
and you should say so:
authenticate(): Observable<boolean> {
return this.http.get<UserVerifyResponse>(
this.apiUrl+'/verify_user'
).pipe(
map((receivedData) => {
return receivedData.success;
}),
tap((data) => {console.log("User authenticated", data)}),
catchError(this.handleError)
)
}
The pipe alters the Observable from UserVerifyResponse
to the boolean
that is ultimately returned.
Note that I have deleted most of the typing you had. In general, you should only specify type when:
get()
itself, since the TypeScript compiler cannot correctly infer the type, orauthenticate()
, since while TypeScript can infer the type, someone reading your code later probably cannot.