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’s typeof always returns lowercase.

  • Comparing to runtime values that are not typeof results: "null" (use x === null), "array" (use Array.isArray(x)), "NaN" (use Number.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

Remediation

Use one of the eight typeof results, or switch to the appropriate idiom:

// Good
if (typeof x === "string") { ... }
if (x === null) { ... }
if (Array.isArray(x)) { ... }
if (Number.isNaN(x)) { ... }