Skip to content
← Back to rules

eslint/grouped-accessor-pairs 风格

An auto-fix is available for this rule.

它做了什么

在对象字面量和类中要求分组的访问器对

为什么这是个问题?

虽然允许在对象或类定义中的任意位置定义某个属性的获取器(getter)或设置器(setter),但最佳实践是将同一属性的访问器函数分组。

示例

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

js
const foo = {
  get a() {
    return this.val;
  },
  b: 1,
  set a(value) {
    this.val = value;
  },
};

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

js
const foo = {
  get a() {
    return this.val;
  },
  set a(value) {
    this.val = value;
  },
  b: 1,
};

使用 getBeforeSet 选项时的错误代码示例:

js
const foo = {
  set a(value) {
    this.val = value;
  },
  get a() {
    return this.val;
  },
};

使用 getBeforeSet 选项时的正确代码示例:

js
const foo = {
  get a() {
    return this.val;
  },
  set a(value) {
    this.val = value;
  },
};

使用 setBeforeGet 选项时的错误代码示例:

js
const foo = {
  get a() {
    return this.val;
  },
  set a(value) {
    this.val = value;
  },
};

使用 setBeforeGet 选项时的正确代码示例:

js
const foo = {
  set a(value) {
    this.val = value;
  },
  get a() {
    return this.val;
  },
};

配置

第一个选项

类型:"anyOrder" | "getBeforeSet" | "setBeforeGet"

"anyOrder"

访问器可以按任意顺序排列。这是默认行为。

"getBeforeSet"

获取器必须出现在设置器之前。

"setBeforeGet"

设置器必须出现在获取器之前。

第二个选项

此选项是一个具有以下属性的对象:

enforceForTSTypes

类型:boolean

默认值:false

当启用 enforceForTSTypes 时,此规则也适用于 TypeScript 接口和类型别名。

错误的 TypeScript 代码示例:

ts
interface Foo {
  get a(): string;
  someProperty: string;
  set a(value: string);
}

type Bar = {
  get b(): string;
  someProperty: string;
  set b(value: string);
};

正确的 TypeScript 代码示例:

ts
interface Foo {
  get a(): string;
  set a(value: string);
  someProperty: string;
}

type Bar = {
  get b(): string;
  set b(value: string);
  someProperty: string;
};

如何使用

要通过配置文件或 CLI 启用此规则,可以使用:

json
{
  "rules": {
    "grouped-accessor-pairs": "error"
  }
}
bash
oxlint --deny grouped-accessor-pairs

参考资料