如何修复 no-unsafe-any 规则?

Rob*_*ier 5 typescript tslint typescript-types

我正在使用TSLint来检查我的 Angular TypeScript 代码。我启用了no-unsafe-any规则,因为对我来说,永远不要对 type 的属性做出任何假设似乎是一个很好的规则any

问题是该规则报告了我的某些代码的错误,除了禁用该规则之外,我无法以任何方式修复该错误。根据下面的规则无效的代码示例。

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);
      }),
    );
}
Run Code Online (Sandbox Code Playgroud)

Linter 报告 2 行 4 个错误:

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'
Run Code Online (Sandbox Code Playgroud)

2条有问题的线路是:

  • if (error && error.status === httpCodeUnauthorized) {
  • const errorMessage = (error.error && error.error.message) || error.statusText;

问题的根源在于(Rxjs库函数)error的处理程序参数具有类型。我知道可以是任何类型,因此假设它定义了任何属性是不安全的,但我首先在实际引用它们之前检查这些属性是否存在,这对我来说似乎是安全的。catchErroranyerror

我可以/应该做什么来让 linter/TypeScript 编译器相信它是安全的并通过规则?

小智 2

对于 Angular,错误应始终为HttpErrorResponse类型

catchError((error: HttpErrorResponse) => {
//...
}
Run Code Online (Sandbox Code Playgroud)

也就是说,在您的代码中,您可以查看 其中error.error的定义,因此您应该使用类型保护来检查并将其转换为 Error 对象。不是没有必要定义- 它应该由打字稿基本类型定义。anyHttpErrorResponseError

function isError(value: any | undefined): value is Error {
  return error && ((error as Error).message !== undefined);
}
Run Code Online (Sandbox Code Playgroud)

然后使用它

const errorMessage = isError(error.error) ? error.error.message : error.statusText;
Run Code Online (Sandbox Code Playgroud)