Skip to content
← Back to rules

typescript/prefer-readonly Style

💭 This rule requires type information.

它的作用

要求永不被重新赋值的类成员标记为 readonly

为什么这不好?

永不变化的成员应声明为 readonly,以明确类的不变式并 防止意外修改。

示例

以下是此规则的错误代码示例:

ts
class Counter {
  private value = 0;

  getValue() {
    return this.value;
  }
}

以下是此规则的正确代码示例:

ts
class Counter {
  private readonly value = 0;

  getValue() {
    return this.value;
  }
}

配置

此规则接受一个包含以下属性的配置对象:

onlyInlineLambdas

type: boolean

default: false

将检查限制为立即使用内联 lambda 值初始化的成员。

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "options": {
    "typeAware": true
  },
  "rules": {
    "typescript/prefer-readonly": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  options: { typeAware: true },
  rules: {
    "typescript/prefer-readonly": "error",
  },
});
bash
oxlint --type-aware --deny typescript/prefer-readonly

版本

此规则于 v0.0.8 中加入。

参考资料