eslint/valid-typeof Correctness
What it does
Enforce comparing typeof
expressions against valid strings.
Why is this bad?
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.
Examples
Examples of incorrect code for this rule:
typeof foo === "strnig";
typeof foo == "undefimed";
typeof bar != "nunber"; // spellchecker:disable-line
typeof bar !== "fucntion"; // spellchecker:disable-line
Examples of correct code for this rule:
typeof foo === "string";
typeof bar == "undefined";
typeof foo === baz;
typeof bar === typeof qux;
Options
requireStringLiterals
{ type: boolean, default: false }
The requireStringLiterals
option when set to 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
.
With requireStringLiterals
set to true
the following are examples of incorrect code:
typeof foo === undefined;
typeof bar == Object;
typeof baz === "strnig";
typeof qux === "some invalid type";
typeof baz === anotherVariable;
typeof foo == 5;
With requireStringLiterals
set to true
the following are examples of correct code:
typeof foo === "undefined";
typeof bar == "object";
typeof baz === "string";
typeof bar === typeof qux;
How to use
To enable this rule in the CLI or using the config file, you can use:
oxlint --deny valid-typeof
{
"rules": {
"valid-typeof": "error"
}
}