classFieldDeclarations
Reports assigning literal values to
thisin constructors instead of using class field declarations.
✅ This rule is included in the ts untyped preset.
When a class constructor assigns a literal value to a property, the assignment can be replaced with a class field declaration. Class field declarations are more concise and clearly express the intent of initializing properties with default values.
This rule only reports assignments of literal values (strings, numbers, booleans, null).
Assignments involving variables, function calls, or other dynamic expressions are not flagged.
Examples
Section titled “Examples”class Example { constructor() { this.value = "hello"; }}class MyError extends Error { constructor(message: string) { super(message); this.name = "MyError"; }}class Counter { constructor() { this.count = 0; this.enabled = true; }}class Example { value = "hello";}class MyError extends Error { name = "MyError";
constructor(message: string) { super(message); }}class Counter { count = 0; enabled = true;}class Example { constructor(value: string) { this.value = value; }}Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you prefer to keep all property initialization in the constructor for consistency, or if your codebase targets environments that do not support class field declarations, you may disable this rule.
Some teams may also prefer the constructor style when properties need to be initialized in a specific order relative to super() calls.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- ESLint:
unicorn/prefer-class-fields