valid-typeof

强制将 typeof 表达式与有效字符串进行比较

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

💡 hasSuggestions

此规则报告的一些问题可通过编辑器建议手动修复

对于绝大多数用例,typeof 运算符的结果是以下字符串字面之一:"undefined""object""boolean""number""string""function""symbol""bigint"。将 typeof 运算符的结果与其他字符串字面进行比较通常是输入错误。

¥For a vast majority of use cases, the result of the typeof operator is one of the following string literals: "undefined", "object", "boolean", "number", "string", "function", "symbol", and "bigint". It is usually a typing mistake to compare the result of a typeof operator to other string literals.

规则详情

¥Rule Details

此规则强制将 typeof 表达式与有效的字符串字面进行比较。

¥This rule enforces comparing typeof expressions to valid string literals.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint valid-typeof: "error"*/

typeof foo === "strnig"
typeof foo == "undefimed"
typeof bar != "nunber"
typeof bar !== "fucntion"

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint valid-typeof: "error"*/

typeof foo === "string"
typeof bar == "undefined"
typeof foo === baz
typeof bar === typeof qux

选项

¥Options

此规则有一个对象选项:

¥This rule has an object option:

  • "requireStringLiterals": true 允许将 typeof 表达式仅与字符串字面量或其他 typeof 表达式进行比较,并且不允许与任何其他值进行比较。默认为 false

    ¥"requireStringLiterals": true allows the comparison of typeof expressions with only string literals or other typeof expressions, and disallows comparisons to any other value. Default is false.

requireStringLiterals

使用 { "requireStringLiterals": true } 选项的错误代码示例:

¥Examples of incorrect code with the { "requireStringLiterals": true } option:

在线运行
/*eslint valid-typeof: ["error", { "requireStringLiterals": true }]*/

typeof foo === undefined
typeof bar == Object
typeof baz === "strnig"
typeof qux === "some invalid type"
typeof baz === anotherVariable
typeof foo == 5

使用 { "requireStringLiterals": true } 选项的正确代码示例:

¥Examples of correct code with the { "requireStringLiterals": true } option:

在线运行
/*eslint valid-typeof: ["error", { "requireStringLiterals": true }]*/

typeof foo === "undefined"
typeof bar == "object"
typeof baz === "string"
typeof bar === typeof qux

何时不使用

¥When Not To Use It

如果你将在主机对象上使用 typeof 运算符,你可能需要关闭此规则。

¥You may want to turn this rule off if you will be using the typeof operator on host objects.

版本

此规则是在 ESLint v0.5.0 中引入。

进阶读物

资源

ESLint 中文网
粤ICP备13048890号