Vilius Gudžiūnas
Vilius Gudžiūnas

Reputation: 319

Is there an eslint rule for detecting unused class properties?

I am working with an Angular project and my ESLint setup does not detect when a private class variable is unused, e.g.

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

The private property above - exampleProperty will not be highlighted with the current ESLint setup that I have.

My .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": {}
    }
  ]
}

How can I get the linter to pick this up?

Upvotes: 6

Views: 3684

Answers (2)

Josh
Josh

Reputation: 3515

If you're using true # private class fields, the core ESLint rule no-unused-private-class-members will detect unused ones.

For TypeScript private type privacy, there is no such rule right now. But there is an open typescript-eslint issue to augment no-unused-private-class members that's accepting PRs. Meaning: if you can code it right, it'd be accepted into typescript-eslint.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074809

You can get TypeScript to pick this up for you, by turning on the noUnusedLocals option in tsconfig.json. ("Locals" apparently includes unused private properties, which are after all local to the class.)

Here's a playground with that class with the option turned on, which gives the error:

'exampleProperty' is declared but its value is never read.(6133)

(I added a constructor and set the property, just so the error isn't mixed with / obscured by the error about it not being initialized.)

Upvotes: 6

Related Questions