prefer-class-properties
Moves simple literal defaults out of the constructor and into class fields.
Rule details Suggestion
Section titled “Rule details ”SuggestionBy default, this rule reports this.property = value assignments inside constructors when value is known at class
definition time. That includes primitive literals, literal arrays, and object literals without spreads or computed
properties.
The rule only checks constructor assignments to this properties. If the value depends on constructor parameters or
runtime work, it is left alone.
Examples
Section titled “Examples” Incorrect
class User { constructor() { this.name = "Unknown"; this.age = 0; this.flags = [true, false]; }} Correct
class User { name = "Unknown"; age = 0; flags = [true, false];}
class Service { constructor(options: Options) { this.options = options; }}Options
Section titled “Options”| Option | Default | What it does |
|---|---|---|
"always" | yes | Reports constructor assignments of simple literal values and prefers class fields. |
"never" | no | Reports non-static class property declarations and prefers constructor initialization. |
import ceaseNonsense from "eslint-plugin-cease-nonsense";
export default [ { plugins: { "cease-nonsense": ceaseNonsense, }, rules: { "cease-nonsense/prefer-class-properties": ["error", "never"], }, },];Related rules
Section titled “Related rules” no-async-constructor Keeps constructors focused on setup
no-instance-methods-without-this Moves class code to a better place when `this` is not used