Skip to content

unicorn/prefer-class-fields Style

🛠️💡 An auto-fix and a suggestion are available for this rule for some violations.

What it does

Prefers class field declarations over this assignments in constructors for static values.

Why is this bad?

Class field declarations are more readable and less error-prone than assigning static values to this in the constructor. Using class fields keeps the constructor cleaner and makes the intent clearer.

Examples

Examples of incorrect code for this rule:

js
class Foo {
  constructor() {
    this.bar = 1;
  }
}

Examples of correct code for this rule:

js
class Foo {
  bar = 1;
}

How to use

To enable this rule in the CLI or using the config file, you can use:

bash
oxlint --deny unicorn/prefer-class-fields
json
{
  "rules": {
    "unicorn/prefer-class-fields": "error"
  }
}

References

Released under the MIT License.