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.
- 扁平配置
- 旧版配置
export default tseslint.config({
rules: {
"@typescript-eslint/prefer-readonly": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/prefer-readonly": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ 错误
- ✅ 正确
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 Playgroundclass 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';
}
// This is modified later on by the class
#modifiedLaterPrivateField = 'unchanged';
public mutatePrivateField() {
this.#modifiedLaterPrivateField = 'mutated';
}
}
Open in Playground选项
该规则接受以下选项:
type Options = [
{
/** 是否将检查限制为仅立即分配 lambda 值的成员。 */
onlyInlineLambdas?: boolean;
},
];
const defaultOptions: Options = [{ onlyInlineLambdas: false }];
¥Options
onlyInlineLambdas
是否将检查限制为仅立即分配 lambda 值的成员。 Default: false
.
{
"@typescript-eslint/prefer-readonly": [
"error",
{ "onlyInlineLambdas": true },
],
}
{ "onlyInlineLambdas": true }
选项的代码示例:
¥Example of code for the { "onlyInlineLambdas": true }
options:
- ❌ 错误
- ✅ 正确
class Container {
private onClick = () => {
/* ... */
};
}
Open in Playgroundclass Container {
private neverModifiedPrivate = 'unchanged';
}
Open in Playground