Skip to content
← Back to rules

oxc/bad-bitwise-operator 限制

💡 A suggestion is available for this rule.

作用

当使用按位运算符而预期应使用逻辑运算符时,此规则会生效。

为什么这很糟糕?

按位运算符与逻辑运算符的结果不同,而且由于没有应用短路求值,可能会抛出 TypeError 异常。 (短路求值中,会根据左操作数的值跳过右操作数的求值,例如在 x && y 中,xfalse。)

在以下代码模式中,很明显应当使用逻辑运算符:

javascript
e && e.x;
e || {};
e || "";

示例

此规则的错误代码示例:

javascript
if (obj & obj.prop) {
  console.log(obj.prop);
}
options = options | {};
input |= "";

此规则的正确代码示例:

javascript
if (obj && obj.prop) {
  console.log(obj.prop);
}
options = options || {};
input ||= "";

如何使用

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

json
{
  "rules": {
    "oxc/bad-bitwise-operator": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "oxc/bad-bitwise-operator": "error",
  },
});
bash
oxlint --deny oxc/bad-bitwise-operator

版本

此规则添加于 v0.0.3。

参考资料