Skip to content
← Back to rules

typescript/no-meaningless-void-operator Correctness

This rule is turned on by default when type-aware linting is enabled.
💭 This rule requires type information.
🛠️ 💡 An auto-fix and a suggestion are available for this rule.

它的作用

void 操作符的参数已经是 voidundefined 类型时,此规则不允许使用它。

为什么这很糟糕?

当你想执行一个表达式并强制其求值为 undefined 时,void 操作符非常有用。然而,对已经是 voidundefined 类型的表达式使用 void 是没有意义的,并且会给代码增加不必要的复杂性。

示例

此规则的错误代码示例:

ts
function foo(): void {
  return;
}

void foo(); // 无意义,foo() 已经返回 void

void undefined; // 无意义,undefined 已经是 undefined

async function bar() {
  void (await somePromise); // 如果 somePromise resolve 为 void,则无意义
}

此规则的正确代码示例:

ts
function getValue(): number {
  return 42;
}

void getValue(); // 有意义,将 number 转换为 void

void console.log("hello"); // 有意义,console.log 返回 undefined,但我们希望显式地写出来

function processData() {
  // 一些处理
}

processData(); // 不需要 void,因为我们不关心返回值

配置

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

checkNever

type: boolean

default: false

是否检查应用于 never 类型表达式的 void

如何使用

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

json
{
  "options": {
    "typeAware": true
  },
  "rules": {
    "typescript/no-meaningless-void-operator": "error"
  }
}
ts
import { defineConfig } from "oxlint";

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

版本

此规则是在 v1.12.0 中添加的。

参考