简体   繁体   English

如何解决任何不安全的任何规则?

[英]How to fix no-unsafe-any rule?

I'm using TSLint to lint my Angular TypeScript code. 我正在使用TSLint整理我的Angular TypeScript代码。 I enabled no-unsafe-any rule, as it seems like a good rule to me to never assume anything about properties of type any . 我启用了no-unsafe-any规则,因为对我来说,永远不假设任何类型any属性似乎是一个好规则。

The problem is the rule reports errors on some of my code, which I'm unable to fix in any way other than disabling the rule. 问题是该规则报告了我的某些代码中的错误,除了禁用该规则外,我无法以其他任何方式修复该错误。 Example of a code that's invalid according to that rule 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);
      }),
    );
}

Linter reports 4 errors on 2 lines: 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'

2 problematic lines are: 2条有问题的行是:

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

The root of the problem is that error argument of a handler given to catchError ( Rxjs library function) has any type. 问题的根源在于,赋予catchErrorRxjs库函数)的处理程序的error参数具有any类型。 I understand error can be of any type, so it's unsafe to assume it has any properties defined, but I'm first checking for the presence of those properties before actually refering to them, which seems safe to me. 我知道error可以是任何类型,因此假设它已定义任何属性都是不安全的,但是在实际引用它们之前,我首先要检查这些属性的存在,这对我来说似乎很安全。

What can/should I do to convince the linter/TypeScript compiler that it's safe and pass the rule? 我怎样做/应该说服linter / TypeScript编译器安全并通过规则?

In case of Angular the error should always be in of type HttpErrorResponse 如果是Angular,则错误应始终为HttpErrorResponse类型

catchError((error: HttpErrorResponse) => {
//...
}

That said, in your code you look into error.error which is defined as any in HttpErrorResponse thus there you should probably use type guard to check and cast it to Error object. 就是说,在您的代码中,您将研究在error.error中定义为HttpErrorResponse any ,因此您可能应该使用类型保护检查并将其转换为Error对象。 Not there is no need to define the Error - it should be defined by typescript base types. 不需要定义Error -应该由打字稿基本类型定义。

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

then use it in 然后用在

const errorMessage = isError(error.error) ? error.error.message : error.statusText;

You have two options, when you know that error always has a specific type, you can just annotate the type. 您有两个选择,当您知道 error始终具有特定类型时,您可以注释该类型。 If you can not be sure, you can use a type guard . 如果不能确定,可以使用类型保护

Type annotation 类型注释

With a type annotation, you can simply tell the compiler, that you expect error to be of a certain type. 使用类型注释,您可以简单地告诉编译器您期望error属于某种类型。 You can avoid the type any completely with this approach: 您可以避免类型any完全用这种方法:

interface Error {
    status: string,
    statusText: string,
    error: { message: string | undefined } | undefined;
}

catchError((error: Error | undefined) => {
    //...
}

Type guard 防护罩

You can use a type guard whenever a value could be of a certain type, but doesn't necessarily have to be of that type. 您可以使用一种类型的后卫,每当值可能是某种类型的,但并不一定是这种类型的。 The type guard will check for the type and within the following block, the variable will be of that checked type: 类型防护将检查类型,并且在以下块中,变量将属于该检查的类型:

function isError(value: any | undefined): value is Error {
    return error && ((error as Error).status !== undefined);
}

catchError(error => {
    if (isError(error)) {
        //Inside this block, error will be of type Error
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何编写启用了no-unsafe-any的类型防护? - How to write type guards with no-unsafe-any enabled? 为什么在启用 no-unsafe-any 时 tslint 将强类型参数的属性标记为 any - Why is tslint flagging properties of strongly typed parameters as any when no-unsafe-any is enabled 如何使用 cloneElement 修复“不安全成员访问”反应 typescript 错误? - How to fix 'unsafe-member-access' react typescript error with cloneElement? 如何处理 catch(err) 块上的 @typescript-eslint/no-unsafe-member-access 规则? - How to handle the @typescript-eslint/no-unsafe-member-access rule on catch(err) blocks? ESLint:“any”的不安全分配和“any”类型值的不安全调用 - ESLint: Unsafe assignment of an `any` and Unsafe call of an `any` typed value 如何修复(error:any)=&gt;可观察 <any> 是不可分配的? - How to fix (error:any)=>Observable<any> is not assignable? 对“任何”值的不安全成员访问 [0] - Unsafe member access [0] on an `any` value Any 值三元运算符的不安全赋值 - Unsafe assignment of an Any value ternary operator TypeScript 不安全地使用“任何”类型的表达式错误 - TypeScript Unsafe use of expression of type 'any' ERROR 在 header object 上不安全地使用表达式 any - Unsafe use of expression any on header object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM