Skip to content
← Back to rules

unicorn/no-null 风格

⚠️🛠️ A dangerous auto-fix is available for this rule for some violations.

它的作用

禁止使用 null 字面量,以鼓励使用 undefined 代替。

为什么这是不好的?

使用 undefined 而非 null 有若干原因。

  • 根据经验,大多数开发者对 nullundefined 的使用不一致且经常互换,很少有人清楚何时应使用哪一个。
  • 同时支持 nullundefined 会使输入验证更加复杂。
  • 使用 null 会让 TypeScript 类型声明更冗长:type A = {foo?: string | null}type A = {foo?: string} 相比。

示例

此规则的 错误 代码示例:

javascript
let foo = null;

此规则的 正确 代码示例:

javascript
let foo;

配置

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

checkStrictEquality

type: boolean

默认值: false

当设置为 true 时,该规则还会检查对 null 的严格相等/不相等比较(===!==)。

如何使用

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

json
{
  "rules": {
    "unicorn/no-null": "error"
  }
}
bash
oxlint --deny unicorn/no-null

参考资料