Skip to content
← Back to rules

unicorn/no-null Style

⚠️ 🛠️ 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} vs type A = {foo?: string}

示例

此规则的错误代码示例:

javascript
let foo = null;

此规则的正确代码示例:

javascript
let foo;

配置

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

checkStrictEquality

type: boolean

default: false

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

如何使用

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

json
{
  "rules": {
    "unicorn/no-null": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/no-null": "error",
  },
});
bash
oxlint --deny unicorn/no-null

版本

此规则在 v0.0.21 中添加。

参考资料