I keep getting confused about how to type my HttpResponse. I'm trying to match what my api is giving me back but my typescript help in vim keeps telling me:
typescript: Type 'Observable<unknown>' is not assignable to type 'Observable<string | HttpErrorResponse>'.
Type 'unknown' is not assignable to type 'string | HttpErrorResponse'. [2322]
This is what my post looks like:
forgotPassword(args: {studentId: string, emailAddress: string}): RxObservable<HttpErrorResponse | string> {
const body = {
studentId: args.studentId,
emailAddress: args.emailAddress
}
console.log("forgot password", body)
return this.http
.post<HttpErrorResponse | string>(
`${this.nextApiEndpoint}Authentication/ForgotPassword`,
body,
{}
)
.pipe(
switchMap((data: string) => data),
catchError((err) => {
return err;
})
);
}
I'm trying to use switchMap to make sure the data piped out is string, but I really don't need that because that is what my http response is already, a string.
You can just remove the
HttpErrorResponsefrom the post and letcatchErrorcontain the typeHttpErrorResponse. Also since we are not calling another API call with the previous data I swapped theswitchMapwith amap.To sum it up, we don't need to add extra lines for
HttpErrorResponsejust the success return type is enough and typescript will allow this.Stackblitz Demo with no compilation errors