eslint/valid-typeof 正确性
它做了什么
强制对 typeof 表达式与有效的字符串进行比较。
为什么这是不好的?
在绝大多数使用场景中,typeof 操作符的结果是以下字符串字面量之一:"undefined"、"object"、"boolean"、"number"、"string"、"function"、"symbol",以及 "bigint"。将 typeof 操作符的结果与其他字符串字面量进行比较通常是类型错误。
示例
此规则的 错误 代码示例:
js
typeof foo === "strnig";
typeof foo == "undefimed";
typeof bar != "nunber"; // spellchecker:disable-line
typeof bar !== "fucntion"; // spellchecker:disable-line此规则的 正确 代码示例:
js
typeof foo === "string";
typeof bar == "undefined";
typeof foo === baz;
typeof bar === typeof qux;配置
此规则接受一个配置对象,包含以下属性:
requireStringLiterals
type: boolean
default: false
当 requireStringLiterals 设置为 true 时,仅允许 typeof 表达式与字符串字面量或其他 typeof 表达式进行比较,禁止与任何其他值进行比较。默认值为 false。
当 requireStringLiterals 设置为 true 时,以下为 错误 代码示例:
js
typeof foo === undefined;
typeof bar == Object;
typeof baz === "strnig";
typeof qux === "some invalid type";
typeof baz === anotherVariable;
typeof foo == 5;当 requireStringLiterals 设置为 true 时,以下为 正确 代码示例:
js
typeof foo === "undefined";
typeof bar == "object";
typeof baz === "string";
typeof bar === typeof qux;如何使用
通过配置文件或 CLI 启用此规则,可以使用:
json
{
"rules": {
"valid-typeof": "error"
}
}bash
oxlint --deny valid-typeof