Skip to content
← Back to rules

eslint/no-undefined 限制

它的作用

禁止将 undefined 用作标识符

为什么这是不好的?

直接使用 undefined 可能导致错误,因为在 JavaScript 中它可能被遮蔽或重写。 更安全且意图更明确的做法是使用 null,或者依赖隐式的 undefined(例如,缺少返回值),以避免意外问题。

示例

此规则的 错误 代码示例:

javascript
var foo = undefined;

var undefined = "foo";

if (foo === undefined) {
  // ...
}

function baz(undefined) {
  // ...
}

bar(undefined, "lorem");

此规则的 正确 代码示例:

javascript
var foo = void 0;

var Undefined = "foo";

if (typeof foo === "undefined") {
  // ...
}

global.undefined = "foo";

bar(void 0, "lorem");

如何使用

通过配置文件或 CLI 启用此规则,可以使用:

json
{
  "rules": {
    "no-undefined": "error"
  }
}
bash
oxlint --deny no-undefined

参考资料