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.

eslint.config.mjs
export default tseslint.config({
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 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 Playground

何时不使用它

¥When Not To Use It

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

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


Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.

See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.

资源