Skip to main content

prefer-readonly

Require private members to be marked as readonly if they're never modified outside of the constructor.

🔧

此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复

💭

该规则需要 类型信息 才能运行。


私有成员变量(无论是使用 private 修饰符还是私有 # 字段)都不允许在其声明类之外进行修改。 如果该类从不修改它们的值,则可以安全地将它们标记为 readonly

英: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.

如果私有成员从未在构造函数之外进行修改,则此规则报告的私有成员将被标记为 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"
}
};
在线运行试试这个规则 ↗

示例

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 Playground

选项

onlyInlineLambdas

你可以将 "onlyInlineLambdas": true 作为对象内的规则选项传递,以将检查限制为仅检查立即分配 lambda 值的成员。

英: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 }]
}

{ "onlyInlineLambdas": true } 选项的代码示例:

英:Example of code for the { "onlyInlineLambdas": true } options:

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

何时不使用它

如果你不尝试强制执行强大的不可变性保证,则此规则对于你的项目可能限制过多。

英:If you aren't trying to enforce strong immutability guarantees, this rule may be too restrictive for your project.

选项

该规则接受以下选项

type Options = [
{
onlyInlineLambdas?: boolean;
},
];

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

资源