eslint/eqeqeq 严格
功能说明
要求使用 === 和 !== 操作符,禁止使用 == 和 !=。
为什么这是个问题?
使用非严格相等操作符会导致因类型转换而产生意外行为,这可能引发难以发现的错误。
示例
示例 JSON 配置:
json
{
"eqeqeq": ["error", "always", { "null": "ignore" }]
}"always"(默认值)
此规则下错误代码示例:
js
/* eqeqeq: "error" */
if (x == 42) {
}
if ("" == text) {
}
if (obj.getStuff() != undefined) {
}此规则下正确代码示例:
js
/* eqeqeq: "error" */
if (x === 42) {
}
if ("" === text) {
}
if (obj.getStuff() !== undefined) {
}"smart"
使用 "smart" 选项时,此规则下错误代码示例:
js
/* eqeqeq: ["error", "smart"] */
if (x == 42) {
}
if ("" == text) {
}使用 "smart" 选项时,此规则下正确代码示例:
js
/* eqeqeq: ["error", "smart"] */
if (typeof foo == "undefined") {
}
if (foo == null) {
}
if (foo != null) {
}{"null": "ignore"}(在 "always" 作为第一个选项时)
使用 { "null": "ignore" } 选项时,此规则下错误代码示例:
js
/* eqeqeq: ["error", "always", { "null": "ignore" }] */
if (x == 42) {
}
if ("" == text) {
}使用 { "null": "ignore" } 选项时,此规则下正确代码示例:
js
/* eqeqeq: ["error", "always", { "null": "ignore" }] */
if (foo == null) {
}
if (foo != null) {
}{"null": "always"}(默认值 —— 在 "always" 作为第一个选项时)
使用 { "null": "always" } 选项时,此规则下错误代码示例:
js
/* eqeqeq: ["error", "always", { "null": "always" }] */
if (foo == null) {
}
if (foo != null) {
}使用 { "null": "always" } 选项时,此规则下正确代码示例:
js
/* eqeqeq: ["error", "always", { "null": "always" }] */
if (foo === null) {
}
if (foo !== null) {
}{"null": "never"}(在 "always" 作为第一个选项时)
使用 { "null": "never" } 选项时,此规则下错误代码示例:
js
/* eqeqeq: ["error", "always", { "null": "never" }] */
if (x == 42) {
}
if ("" == text) {
}
if (foo === null) {
}
if (foo !== null) {
}使用 { "null": "never" } 选项时,此规则下正确代码示例:
js
/* eqeqeq: ["error", "always", { "null": "never" }] */
if (x === 42) {
}
if ("" === text) {
}
if (foo == null) {
}
if (foo != null) {
}配置
第一个选项
type: "always" | "smart"
"always"
始终要求使用三重相等比较,即 === / !==。 这是默认行为。
"smart"
允许某些安全的比较使用 == / !=(如 typeof、字面量、空值)。
第二个选项
该选项是一个包含以下属性的对象:
null
type: "always" | "never" | "ignore"
"always"
在与 null 比较时始终要求使用三重相等,即 === null / !== null。 这是默认行为。
"never"
在与 null 比较时从不强制使用三重相等,始终使用 == null / != null。
"ignore"
忽略对 null 的比较,允许使用 == null / != null 或 === null / !== null。
如何使用
要通过配置文件或 CLI 启用此规则,可以使用:
json
{
"rules": {
"eqeqeq": "error"
}
}bash
oxlint --deny eqeqeq