prefer-readonly
Require private members to be marked as
readonly
if they're never modified outside of the constructor.
Some problems reported by this rule are automatically fixable by the --fix
ESLint command line option.
This rule requires type information to run.
Private member variables (whether using the private
modifier or private #
fields) are never permitted to be modified outside of their declaring class.
If that class never modifies their value, they may safely be marked as readonly
.
This rule reports on private members are marked as readonly
if they're never modified outside of the constructor.
module.exports = {
"rules": {
"@typescript-eslint/prefer-readonly": "error"
}
};
Try this rule in the playground ↗
Examples
- ❌ Incorrect
- ✅ Correct
class Container {
// These member variables could be marked as readonly
private neverModifiedMember = true;
private onlyModifiedInConstructor: number;
#neverModifiedPrivateField = 3;
public constructor(
onlyModifiedInConstructor: number,
// Private parameter properties can also be marked as readonly
private neverModifiedParameter: string,
) {
this.onlyModifiedInConstructor = onlyModifiedInConstructor;
}
}
Open in Playgroundclass Container {
// Public members might be modified externally
public publicMember: boolean;
// Protected members might be modified by child classes
protected protectedMember: number;
// This is modified later on by the class
private modifiedLater = 'unchanged';
public mutate() {
this.modifiedLater = 'mutated';
}
// This is modified later on by the class
#modifiedLaterPrivateField = 'unchanged';
public mutatePrivateField() {
this.#modifiedLaterPrivateField = 'mutated';
}
}
Open in PlaygroundOptions
This rule accepts the following options:
type Options = [
{
/** Whether to restrict checking only to members immediately assigned a lambda value. */
onlyInlineLambdas?: boolean;
},
];
const defaultOptions: Options = [{ onlyInlineLambdas: false }];
onlyInlineLambdas
You may pass "onlyInlineLambdas": true
as a rule option within an object to restrict checking only to members immediately assigned a lambda value.
{
"@typescript-eslint/prefer-readonly": [
"error",
{ "onlyInlineLambdas": true },
],
}
Example of code for the { "onlyInlineLambdas": true }
options:
- ❌ Incorrect
- ✅ Correct
class Container {
private onClick = () => {
/* ... */
};
}
Open in Playgroundclass Container {
private neverModifiedPrivate = 'unchanged';
}
Open in PlaygroundWhen Not To Use It
If you aren't trying to enforce strong immutability guarantees, this rule may be too restrictive for your project.
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.
See Troubleshooting > Linting with Type Information > Performance if you experience performance degredations after enabling type checked rules.