Skip to content
← Back to rules

typescript/prefer-readonly Style

💭 This rule requires type information.

What it does ​

Require class members that are never reassigned to be marked readonly.

Why is this bad? ​

Members that never change should be declared readonly to make class invariants explicit and prevent accidental mutation.

Examples ​

Examples of incorrect code for this rule:

ts
class Counter {
  private value = 0;

  getValue() {
    return this.value;
  }
}

Examples of correct code for this rule:

ts
class Counter {
  private readonly value = 0;

  getValue() {
    return this.value;
  }
}

Configuration ​

This rule accepts a configuration object with the following properties:

onlyInlineLambdas ​

type: boolean

default: false

Restrict checks to members immediately initialized with inline lambda values.

How to use ​

To enable this rule using the config file or in the CLI, you can use:

json
{
  "options": {
    "typeAware": true
  },
  "rules": {
    "typescript/prefer-readonly": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  options: { typeAware: true },
  rules: {
    "typescript/prefer-readonly": "error",
  },
});
bash
oxlint --type-aware --deny typescript/prefer-readonly

Version ​

This rule was added in v0.0.8.

References ​