Currently incorporating TSLint for maintaining the quality of my Angular TypeScript code. I've opted to activate the 'no-unsafe-any' rule from TSLint, as it appears beneficial to avoid making assumptions about properties with type 'any'.
An issue has arisen where this rule is flagging errors in some sections of my code that I am struggling to rectify without disabling the rule altogether. An example snippet of code that violates this rule is provided below.
public intercept(request: HttpRequest<{}>, next: HttpHandler): Observable<HttpEvent<{}>> {
return next
.handle(request)
.pipe(
catchError(error => {
if (error && error.status === httpCodeUnauthorized) {
// Auto logout if unathorized
this.authenticationService.logout();
}
const errorMessage = (error.error && error.error.message) || error.statusText;
return throwError(errorMessage);
}),
);
}
The linter is showing 4 errors across 2 lines:
ERROR: /home/robert/programming/npc/gui/src/app/core/authentication/unauthorized.interceptor.ts[24, 24]: Unsafe use of expression of type 'any'.
ERROR: /home/robert/programming/npc/gui/src/app/core/authentication/unauthorized.interceptor.ts[29, 33]: Unsafe use of expression of type 'any'.
ERROR: /home/robert/programming/npc/gui/src/app/core/authentication/unauthorized.interceptor.ts[29, 48]: Unsafe use of expression of type 'any'.
ERROR: /home/robert/programming/npc/gui/src/app/core/authentication/unauthorized.interceptor.ts[29, 72]: Unsafe use of expression of type 'any'
The problematic lines are:
if (error && error.status === httpCodeUnauthorized) {
const errorMessage = (error.error && error.error.message) || error.statusText;
The main challenge originates from the fact that the error
parameter in the handler passed to the catchError
function from the RxJS library has a type of 'any'. While acknowledging that error
could be of any type, I am taking precautions by verifying the existence of its properties before utilizing them, which I believe makes the code safe.
Is there a recommended approach to persuading the linter and TypeScript compiler that the code adheres to safety standards and satisfies the rule?