typeof Compared Against Non-Standard String
ID |
javascript.typeof_nonstandard |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
JavaScript |
Tags |
reliability, suspicious-comparison |
Description
Reports comparisons of the form typeof X === "literal" (or !==) where the right-hand string literal is not one of the eight values that typeof can ever return:
"undefined", "object", "boolean", "number", "bigint", "string", "symbol", "function".
Any other string makes the comparison statically false (or true for !==), so the branch behind the test is dead code.
Rationale
The rule catches three distinct mistakes:
-
Typos:
typeof fn === "fucntion"never matches. -
Confused with
instanceof: arrays and dates appear as"object"totypeof, never as"array"or"date". -
Confused with
=== null:typeof x === "null"never matches;typeof nullis"object".
// Bad
if (typeof xs === "array") handle(xs); // never fires
if (typeof fn === "fucntion") fn(); // typo, never fires
if (typeof v === "null") handleNull(); // typeof null === "object"
Remediation
Use Array.isArray, instanceof, or a direct === null check:
// Good
if (Array.isArray(xs)) handle(xs);
if (typeof fn === "function") fn();
if (v === null) handleNull();