Skip to content
← Back to rules

unicorn/prefer-class-fields Style

🛠️ 💡 An auto-fix and a suggestion are available for this rule for some violations.

作用

优先使用类字段声明,而不是在构造函数中通过 this 赋值来设置静态值。

为什么这样不好?

类字段声明比在构造函数中将静态值赋给 this 更易读,也更不容易出错。使用类字段可以让构造函数更简洁,并且让意图更明确。

示例

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

ts
class Foo {
  constructor() {
    this.bar = 1;
  }
}

class MyError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "MyError";
  }
}

class Foo {
  foo = "foo";
  constructor() {
    this.foo = "bar";
  }
}

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

js
class Foo {
  bar = 1;
}

class MyError extends Error {
  name = "MyError";
}

class Foo {
  foo = "bar";
}

如何使用

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

json
{
  "rules": {
    "unicorn/prefer-class-fields": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/prefer-class-fields": "error",
  },
});
bash
oxlint --deny unicorn/prefer-class-fields

版本

此规则于 v1.20.0 中加入。

参考资料