【问题标题】:Is there an eslint rule for detecting unused class properties?是否有用于检测未使用的类属性的 eslint 规则?
【发布时间】:2021-10-25 15:13:44
【问题描述】:

我正在处理一个 Angular 项目,但我的 ESLint 设置未检测到私有类变量何时未使用,例如

@Component{...}
export class ExampleComponent {
  private exampleProperty: string
}

上面的私有属性 - exampleProperty 不会使用我当前的 ESLint 设置突出显示。

我的.eslintrc.json

{
  "root": true,
  "ignorePatterns": ["projects/**/*"],
  "overrides": [
    {
      "files": ["*.ts"],
      "parserOptions": {
        "project": ["tsconfig.json", "e2e/tsconfig.json"],
        "createDefaultProgram": true
      },
      "env": { "browser": true, "jest": true },
      "extends": [
        "eslint:recommended",
        "plugin:@angular-eslint/recommended",
        "plugin:@angular-eslint/template/process-inline-templates",
        "plugin:@typescript-eslint/recommended"
      ],
      "rules": {
        "@angular-eslint/component-selector": [
          "error",
          { "prefix": "app", "style": "kebab-case", "type": "element" }
        ],
        "@angular-eslint/no-host-metadata-property": "off",
        "@typescript-eslint/ban-ts-comment": "off",
        "@typescript-eslint/ban-types": "off",
        "@typescript-eslint/explicit-module-boundary-types": "off",
        "@typescript-eslint/no-explicit-any": "off",
        "@typescript-eslint/no-unused-vars": [
          "error",
          { "argsIgnorePattern": "^_" }
        ],
        "no-case-declarations": "off",
        "no-console": ["error", { "allow": ["warn", "error"] }],
        "no-prototype-builtins": "off",
        "no-unused-vars": "off"
      }
    },
    {
      "files": ["*.html"],
      "extends": ["plugin:@angular-eslint/template/recommended"],
      "rules": {}
    }
  ]
}

我怎样才能让 linter 把它捡起来?

【问题讨论】:

    标签: angular typescript eslint typescript-eslint


    【解决方案1】:

    您可以通过打开tsconfig.json 中的noUnusedLocals 选项让TypeScript 为您挑选。 (“Locals”显然包括未使用的私有属性,它们毕竟是类的本地属性。)

    Here's a playground 与该类的选项打开,这会给出错误:

    'exampleProperty' 已声明,但其值从未被读取。(6133)

    (我添加了一个构造函数并设置了属性,只是为了使错误不会与未初始化的错误混合/模糊。)

    【讨论】:

    • 是的,这会发现错误,但它会使开发人员创建新函数的体验变得更糟,因为编译器会开始失败。这就是为什么我宁愿将其作为 linter 规则的原因。不过感谢您的回答,它帮助我清理了我们已经留下这些不需要的功能的地方的项目
    • @ViliusGudžiūnas - 是的,如果这只是一个警告而不是错误,就像其他几个选项一样,那就太好了。不过这个好像不是这样的。
    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2023-02-05
    • 2019-05-26
    • 1970-01-01
    • 2019-10-20
    相关资源
    最近更新 更多