Urara-Blog/node_modules/.pnpm-store/v3/files/58/c47d118b685dfa6a2cdfa16ce27d3fef29c2bd95c6f8361f96b0b994c20f004de0abe18f3dd35c1bf697440db964ac66d81b0ba1213024733e6524ceb81e57
2022-08-14 01:14:53 +08:00

91 lines
2 KiB
Text

---
description: "Require private members to be marked as `readonly` if they're never modified outside of the constructor."
---
> 🛑 This file is source code, not the primary documentation location! 🛑
>
> See **https://typescript-eslint.io/rules/prefer-readonly** for documentation.
This rule enforces that private members are marked as `readonly` if they're never modified outside of the constructor.
## Rule Details
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`.
Examples of code for this rule:
<!--tabs-->
### ❌ Incorrect
```ts
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;
}
}
```
### ✅ Correct
```ts
class 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';
}
}
```
## Options
This rule, in its default state, does not require any argument.
### `onlyInlineLambdas`
You may pass `"onlyInlineLambdas": true` as a rule option within an object to restrict checking only to members immediately assigned a lambda value.
```jsonc
{
"@typescript-eslint/prefer-readonly": ["error", { "onlyInlineLambdas": true }]
}
```
Example of code for the `{ "onlyInlineLambdas": true }` options:
<!--tabs-->
#### ❌ Incorrect
```ts
class Container {
private onClick = () => {
/* ... */
};
}
```
#### ✅ Correct
```ts
class Container {
private neverModifiedPrivate = 'unchanged';
}
```