readonly fields can only be assigned in a class constructor. If a class has a field that’s not marked readonly but is
only set in the constructor, it could cause confusion about the field’s intended use. To avoid confusion, such fields should be marked
readonly to make their intended use explicit, and to prevent future maintainers from inadvertently changing their use.
Mark the given field with the readonly modifier.
For JavaScript and TypeScript, {rule:javascript:S2933} reports one issue per class and uses secondary locations for each field that should be
marked readonly.
class Person { // Noncompliant: Mark this member as `readonly`.
private birthYear: number;
constructor(birthYear: number) {
this.birthYear = birthYear;
}
}
class Person {
private readonly birthYear: number;
constructor(birthYear: number) {
this.birthYear = birthYear;
}
}
When more than one field in the same class should be marked readonly, the issue remains on the class and each affected field is listed
as a secondary location.
class Person { // Noncompliant: Mark these members as `readonly`.
private birthYear: number;
private age: number;
constructor(birthYear: number, age: number) {
this.birthYear = birthYear;
this.age = age;
}
}
class Person {
private readonly birthYear: number;
private readonly age: number;
constructor(birthYear: number, age: number) {
this.birthYear = birthYear;
this.age = age;
}
}