Typeof Compared to Invalid String
ID |
javascript.valid_typeof |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
JavaScript |
Tags |
reliability, suspicious-comparison |
Description
Reports typeof <expr> === '<literal>' (and !==) comparisons where the literal is not a string the typeof operator can ever return. The eight values returned by typeof are "string", "number", "boolean", "bigint", "symbol", "undefined", "object", and "function" — any other comparison is dead code and almost always a typo or a misunderstanding of typeof.
Rationale
Common mistakes this rule catches:
-
Typos:
typeof x === "stirng","numbr","undefnd". -
Wrong casing:
"String","Number". JavaScript’stypeofalways returns lowercase. -
Comparing to runtime values that are not
typeofresults:"null"(usex === null),"array"(useArray.isArray(x)),"NaN"(useNumber.isNaN(x)).
The comparison is always false (or true for !==), so the branch never runs — silently masking the intended check.
// Bad - dead branches
if (typeof x === "stirng") { ... } // typo
if (typeof x === "null") { ... } // typeof never returns "null"
if (typeof x === "array") { ... } // typeof returns "object" for arrays