Skip to content
TypeScript·Intermediate·Coding·1 min read

Why does typeof null equal object, and how should code narrow it?

Short interview answer

That result is a historical JavaScript behavior. Check value !== null before treating an object-typed value as an object, because a typeof value === 'object' branch otherwise includes null.

Example

TypeScript
function keys(x: object | null) {  if (typeof x === 'object' && x !== null) {    return Object.keys(x); // without the null check, x could be null  }  return [];}

Key takeaway

Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.

← Back to Type narrowing

Related questions