Skip to content
← Back to rules

unicorn/explicit-length-check Pedantic

🛠️ An auto-fix is available for this rule for some violations.

它的作用

强制显式比较值的 lengthsize 属性。

为什么这不好?

使用显式的 lengthsize 属性可以使代码更清晰、易于理解,因为它避免了依赖隐式的真值/假值判断。

示例

此规则的错误代码示例:

javascript
const isEmpty = foo.length == 0;
const isEmpty = foo.length < 1;
const isEmpty = 0 === foo.length;
const isEmpty = 0 == foo.length;
const isEmpty = 1 > foo.length;

const isEmpty = !foo.length;
const isEmpty = !(foo.length > 0);
const isEmptySet = !foo.size;

此规则的正确代码示例:

javascript
const isEmpty = foo.length === 0;

if (foo.length > 0 || bar.length > 0) {
}

const unicorn = foo.length > 0 ? 1 : 2;

配置

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

non-zero

type: "greater-than" | "not-equal"

default: "greater-than"

用于指定如何强制检查非零长度的配置选项。

"greater-than"

强制使用 foo.length > 0 来检查非零。

"not-equal"

强制使用 foo.length !== 0 来检查非零。

如何使用

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

json
{
  "rules": {
    "unicorn/explicit-length-check": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/explicit-length-check": "error",
  },
});
bash
oxlint --deny unicorn/explicit-length-check

版本

此规则在 v0.0.19 中添加。

参考资料