Hi Sonar team,
I am using SonarQube version 4.45.0 and observed the following behavior.
typescript:S7757 | (TypeScript) Class properties should be declared as fields rather than assigned in constructors
Case 1: Mixed constructor assignments
While testing this rule, I noticed that Sonar initially reports only the first eligible static assignment in the constructor. After resolving that issue, Sonar reports the next eligible assignment on a subsequent scan.
export class SampleModel {
public id: string;
public name: string;
public count: number;
constructor() {
this.name = ""
this.id = generateUniqueId();
this.count = 0;
}
}
Initially Sonar reports this.name = "". After fixing it and re-running the analysis, Sonar should report this.count = 0.
However, if a non-static assignment such as this.id = generateUniqueId() or an empty array initialization such as this.items = [] exists in the constructor, Sonar does not report issues for eligible assignments that appear later in the constructor.
However, if the runtime assignment is removed:
export class SampleModel {
public count: number;
constructor() {
this.count = 0;
}
}
the rule reports:
“Prefer class field declaration over this assignment in constructor for static values.”
It appears that the presence of a non-static assignment prevents the rule from reporting other eligible static assignments in the same constructor.
Is this intentional, or should this.count = 0 still be detected and reported?
Case 2: Empty array initialization
The following code is also not reported:
export class SampleModel {
public items: ItemModel[];
public results: ResultModel[];
constructor() {
this.items = [];
this.results = [];
}
}
Is excluding empty array initializations an intentional design choice, or is this a limitation of the current implementation?
Expected behavior
I would expect either:
- Eligible static assignments to be reported individually, even when mixed with non-static assignments in the same constructor, or
- The rule documentation to clarify that it only triggers when the entire constructor can be replaced by field initializers.
Could you please clarify whether this behavior is expected?
Thanks.
