Skip to content
← Back to rules

eslint/no-empty-function 限制

🚧 An auto-fix is planned for this rule, but not implemented at this time.

它的作用

禁止使用空函数。

为什么这是个问题?

空函数会降低代码可读性,因为读者需要猜测这是否为有意为之。因此,为空函数添加清晰的注释是一种良好实践。

示例

此规则的错误示例:

typescript
function foo() {}

const bar = () => {};

class Foo {
  constructor();
  someMethod() {}
  set bar(value) {}
}

此规则的正确示例:

typescript
function foo() {
  // 不执行任何操作
}

function foo() {
  return;
}
const add = (a, b) => a + b;

class Foo {
  // 构造函数体为空,但它声明了一个名为 `_name` 的私有属性
  constructor(private _name: string) {}

  public get name() {
    return this._name;
  }
}

配置

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

allow

type: array

允许为空的函数类型。

默认情况下,不允许任何类型的函数为空,但可以通过此选项允许特定类型的函数为空。

示例:

json
{
  "no-empty-function": ["error", { "allow": ["constructors"] }]
}

allow[n]

type: "functions" | "arrowFunctions" | "generatorFunctions" | "methods" | "generatorMethods" | "getters" | "setters" | "constructors" | "asyncFunctions" | "asyncMethods" | "privateConstructors" | "protectedConstructors" | "decoratedFunctions" | "overrideMethods"

可以被允许为空的函数类型。

"functions"

允许空的普通函数。

js
function foo() {}
"arrowFunctions"

允许空的箭头函数。

js
const foo = () => {};
"generatorFunctions"

允许空的生成器函数。

js
function* foo() {}
"methods"

允许空的方法。

js
class Foo {
  bar() {}
}
"generatorMethods"

允许空的生成器方法。

js
class Foo {
  *bar() {}
}
"getters"

允许空的获取器。

js
class Foo {
  get bar() {}
}
"setters"

允许空的设置器。

js
class Foo {
  set bar(value) {}
}
"constructors"

允许空的构造函数。

js
class Foo {
  constructor() {}
}
"asyncFunctions"

允许空的异步函数。

js
async function foo() {}
"asyncMethods"

允许空的异步方法。

js
class Foo {
  async bar() {}
}
"privateConstructors"

允许空的私有构造函数。

ts
class Foo {
  private constructor() {}
}
"protectedConstructors"

允许空的受保护构造函数。

ts
class Foo {
  protected constructor() {}
}
"decoratedFunctions"

允许空的装饰函数。

js
class Foo {
  @decorator()
  bar() {}
}
"overrideMethods"

允许空的重写方法。

ts
class Foo extends Base {
  override bar() {}
}

如何使用

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

json
{
  "rules": {
    "no-empty-function": "error"
  }
}
bash
oxlint --deny no-empty-function

参考资料