Skip to main content

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.

Member variables with the privacy private 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.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-readonly": "error"
}
};
Try this rule in the playground ↗

Examples

class Container {
// These member variables could be marked as readonly
private neverModifiedMember = true;
private onlyModifiedInConstructor: number;

public constructor(
onlyModifiedInConstructor: number,
// Private parameter properties can also be marked as readonly
private neverModifiedParameter: string,
) {
this.onlyModifiedInConstructor = onlyModifiedInConstructor;
}
}

This rule accepts an options object with the following properties:

interface Options {
onlyInlineLambdas?: boolean;
}

const defaultOptions: Options = [{ onlyInlineLambdas: false }];

Options

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:

class Container {
private onClick = () => {
/* ... */
};
}

Resources