Currently, I am in the midst of updating my project to Angular 6 with TypeScript version 2.7.0. Previously, in Angular 5.2.12, my service methods were written like this:
isPartDraft = (part: number): Observable<boolean> =>
this._http.get(`${this.rest}/isDraft/${part}`)
.catch(MyPartService.handleError);
The function definition was annotated with a return type, however, the type was not asserted within the function body.
Now, it appears that in certain scenarios, this approach is no longer valid as the tsc
compiler throws the following error:
TS2322:
Type 'Observable<Object>' is not assignable to type 'Observable<boolean>'.
Type 'Object' is not assignable to type 'boolean'.
As a result, I have to assert the return type within the function body, following the guidelines outlined in the current Angular documentation:
isPartDraft = (part: number) =>
this._http.get<boolean>(`${this.rest}/isDraft/${part}`)
.pipe(catchError(MyService.handleError));
Fortunately, everything seems to be working fine so far, despite the fact that we have not modified our annotations since angular2-rc6. However, it's possible that this issue has been present for some time.
Interestingly, I do not encounter any TypeScript errors in the following cases:
getPasswordPolicy(): Observable<PasswordPolicy> {
return this._http.get(`${this.rest}/securityPolicy/`)
.pipe(
map((securityPolicy: any) => securityPolicy.passwordPolicy),
catchError(error => observableThrowError(error))
);
}
Similarly, in another service:
getPartsAtDate = (id: number, date: string, time: string): Observable<number[]> =>
this._http.get(`${this.rest}/partsOnDate/${id}/${date}/${time}`)
.pipe(catchError(MyService.handleError));
getAllNewOrders = (id: number): Observable<Orders[]> =>
this._http.get(`${this.rest}/${id}`)
.pipe(catchError(MyService.handleError));
This raises the question of how the pipe()
, catchError()
, and map()
operators are interacting to cause this inconsistency. Why is it that I cannot annotate the function definition in the first case, but can do so in the latter three?
Instead of blindly fixing the errors pointed out by tsc, I am eager to comprehend the underlying issue, especially given the different outcomes in seemingly identical situations.
For reference, here is the implementation of the error handler (which is the same in each service):
private static handleError(error: any) {
console.log('error ' + error);
return observableThrowError(error.status || 'Server error');
}