src/content/docs/linter/rules/use-readonly-class-properties.mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs> <TabItem label="TypeScript and TSX" icon="seti:typescript"> ## Summary - Rule available since: `v2.1.0` - Diagnostic Category: [`lint/style/useReadonlyClassProperties`](/reference/diagnostics#diagnostic-category) - This rule isn't recommended, so you need to enable it. - This rule has an [**unsafe**](/linter/#unsafe-fixes) fix. - The default severity of this rule is [**information**](/reference/diagnostics#information). - Sources: - Same as [`@typescript-eslint/prefer-readonly`](https://typescript-eslint.io/rules/prefer-readonly){
"linter": {
"rules": {
"style": {
"useReadonlyClassProperties": "error"
}
}
}
}
Enforce marking members as readonly if they are never modified outside the constructor.
This rule ensures that class properties, especially private ones, are marked as readonly if their values
remain constant after being initialized. This helps improve code readability, maintainability, and ensures
immutability where applicable.
It can be configured to check only private members or all class properties.
class Container {
private onlyModifiedInConstructor = 1;
constructor(
member1: number,
) {
this.onlyModifiedInConstructor = onlyModifiedInConstructor;
}
}
class Container {
constructor(
private constructorParameter: number,
) {
}
}
class Container {
private neverModifiedMember = true;
}
class Container {
#neverModifiedPrivateField = 3;
}
class Container {
private readonly neverModifiedMember = true;
private readonly onlyModifiedInConstructor: number;
readonly #neverModifiedPrivateField = 3;
public constructor(
onlyModifiedInConstructor: number,
private readonly neverModifiedParameter: string,
) {
this.onlyModifiedInConstructor = onlyModifiedInConstructor;
}
}
checkAllPropertiesChecks whether all class properties (including public and protected) should be analyzed.
By default, checkAllProperties is set to false.
{
"linter": {
"rules": {
"style": {
"useReadonlyClassProperties": {
"options": {
"checkAllProperties": true
}
}
}
}
}
}
class Example {
public constantValue = 42;
constructor(value: number) {
this.constantValue = value;
}
}
class Example {
constructor(protected constructorParameter: string) {
}
}