【问题标题】:How to bypass warning Unexpected any. Specify a different type @typescript-eslint/no-explicit-any如何绕过警告 Unexpected any。指定不同的类型 @typescript-eslint/no-explicit-any
【发布时间】:2020-02-16 09:41:48
【问题描述】:

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

在我们的 React typescript 项目中遇到这个 lint 错误:

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

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

试过这个:// eslint:@typescript-eslint/no-explicit-any: "off" 不工作

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

【问题讨论】:

  • 你不能只修复错误吗?
  • @PierreDuc 不,我们想在我们的案例中绕过这个错误

标签: typescript eslint


【解决方案1】:

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

或者您可以通过以下方式忽略仅一段代码的规则 /* eslint-disable rule-name */ your-block-of-code /* eslint-enable rule-name */这里的cmets必须是block cmets。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      以下内容对您有用。

      /* eslint-disable @typescript-eslint/no-explicit-any */
      

      查看eslint documentation

      【讨论】:

        【解决方案4】:

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

        【讨论】:

        • 您可以详细说明您的答案,以阐明为什么这种方法可以解决问题
        【解决方案5】:

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

        例子:

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

        在 .eslintrc.json 文件中

        【讨论】:

          【解决方案6】:

          如果您期望对象中有(键,值)对,但不知道键可能是什么,您可以定义如下类型。在 someObject 未知的地方,而不是使用任何使用 Record eslint 就可以了。

              type MyType = {
                  name: string;
                  someObject: Record<string, unknown>;
               }
          

          【讨论】:

            【解决方案7】:

            如typescript-eslint所述:

            • 如果您想要一个表示“任何对象”的类型,您可能需要Record&lt;string, unknown&gt;。
            • 如果您想要一个表示“任何值”的类型,您可能需要unknown 代替

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

            {[prop: string]: number | unknown} // object.x = number | unknown
            {[prop: string]: {[prop:string]: number | undefined}} | boolean // object.x can be a boolean or another object that contains key strings with numeric or undefined values
            

            一个选项可以避免未知的使用并带来更大的 可读性是在 any 的函数的情况下应用泛型 部分参数和返回值。例如,这声明了一个类型 并返回一个相同的列表

            export function getObjectValues<T>(objects: {
            [prop: string]: T[] }): T[] { . . .  } 
            

            【讨论】:

              猜你喜欢
              • 2021-11-09
              • 2020-03-11
              • 1970-01-01
              • 2020-03-27
              • 1970-01-01
              • 2021-03-02
              • 2021-04-26
              • 2020-07-07
              • 1970-01-01
              相关资源
              最近更新 更多