如何绕过警告 Unexpected any。指定不同的类型 @typescript-eslint/no-explicit-any

xam*_*mir 25 typescript eslint

我们有严格的零棉绒问题政策。这意味着需要修复所有错误和警告。

在我们的 React 打字稿项目中面对这个 lint 错误:

warning Unexpected any. Specify a different type @typescript-eslint/no-explicit-any

在 Google 和 lint 网站上搜索。我没有找到这样的解决方案!

试过这个:// eslint:@typescript-eslint/no-explicit-any: "off"这是行不通的

有谁知道如何eslint在 React 打字稿项目中绕过这个规则?

小智 42

在 Angular 中,我们将其添加到 TypeScript 规则中。不在一般规则中,因为有时这不起作用。

例子:

"rules": {
             
   "@typescript-eslint/no-explicit-any": ["off"]
}
Run Code Online (Sandbox Code Playgroud)

.eslintrc.json文件中


Cha*_*mal 30

以下将对您有用。

/* eslint-disable @typescript-eslint/no-explicit-any */
Run Code Online (Sandbox Code Playgroud)

检查eslint 文档


pxe*_*eba 18

正如typescript-eslint所描述的:

  • 如果您想要一种含义为“任何对象”的类型,您可能需要Record<string, unknown>改为。
  • 如果您想要一个表示“任何值”的类型,您可能unknown需要

事实上,您通常可以用更好的选项来替换任何选项。为此,您可以使用@RollingInTheDeep提到的记录类型,或者您可以使用索引签名,例如:

{[key1: string]: number | unknown} // object.x = number | unknown
{[key2: string]: {[key3:string]: number | undefined}} | boolean // object.x can be a boolean or another object that contains key strings with numeric or undefined values
Run Code Online (Sandbox Code Playgroud)


小智 14

在尝试绕过相同规则时对我有用的东西,特别是对于重载方法是使用: // eslint-disable-next-line如果你可以简单地在问题行的正上方添加一条评论。

Or you can ignore the rule for just a section of the code by /* eslint-disable rule-name */ your-block-of-code /* eslint-enable rule-name */ The comments here must be block comments.


Sea*_*ean 9

你能用unknown吗?例如HttpResponse<unknown>


use*_*826 6

如果您期望对象中存在(键,值)对,但不知道键是什么,您可以定义如下类型。其中 someObject 未知,但不使用任何 Record<string,unknown> eslint 就可以解决这个问题。

    type MyType = {
        name: string;
        someObject: Record<string, unknown>;
     }
Run Code Online (Sandbox Code Playgroud)


小智 5

"@typescript-eslint/no-explicit-any": ["off"]

  • 您可以详细说明您的答案,以阐明为什么这种方法可以解决问题 (4认同)
  • /sf/answers/4260792371/ (2认同)