1# Requires that private members are marked as `readonly` if they're never modified outside of the constructor (`prefer-readonly`)
2
3This rule enforces that private members are marked as `readonly` if they're never modified outside of the constructor.
4
5## Rule Details
6
7Member variables with the privacy `private` are never permitted to be modified outside of their declaring class.
8If that class never modifies their value, they may safely be marked as `readonly`.
9
10Examples of **incorrect** code for this rule:
11
12```ts
13class Container {
14  // These member variables could be marked as readonly
15  private neverModifiedMember = true;
16  private onlyModifiedInConstructor: number;
17
18  public constructor(
19    onlyModifiedInConstructor: number,
20    // Private parameter properties can also be marked as readonly
21    private neverModifiedParameter: string,
22  ) {
23    this.onlyModifiedInConstructor = onlyModifiedInConstructor;
24  }
25}
26```
27
28Examples of **correct** code for this rule:
29
30```ts
31class Container {
32  // Public members might be modified externally
33  public publicMember: boolean;
34
35  // Protected members might be modified by child classes
36  protected protectedMember: number;
37
38  // This is modified later on by the class
39  private modifiedLater = 'unchanged';
40
41  public mutate() {
42    this.modifiedLater = 'mutated';
43  }
44}
45```
46
47## Options
48
49This rule, in its default state, does not require any argument.
50
51### `onlyInlineLambdas`
52
53You may pass `"onlyInlineLambdas": true` as a rule option within an object to restrict checking only to members immediately assigned a lambda value.
54
55```cjson
56{
57    "@typescript-eslint/prefer-readonly": ["error", { "onlyInlineLambdas": true }]
58}
59```
60
61Example of **correct** code for the `{ "onlyInlineLambdas": true }` options:
62
63```ts
64class Container {
65  private neverModifiedPrivate = 'unchanged';
66}
67```
68
69Example of **incorrect** code for the `{ "onlyInlineLambdas": true }` options:
70
71```ts
72class Container {
73  private onClick = () => {
74    /* ... */
75  };
76}
77```
78
79## Related to
80
81- TSLint: ['prefer-readonly'](https://palantir.github.io/tslint/rules/prefer-readonly)
82