typeof 'object' and Its Quirks
What you'll learn: Why typeof x === 'object' is trickier than other typeof checks and catches more than you might expect.
The Problem with 'object'
When you check typeof value === 'object' in JavaScript (and TypeScript), you'd expect it to identify plain objects like { name: "Alice" }. And it does! But it also returns true for arrays and null, which creates unexpected behavior.
This is a quirk inherited from JavaScript itself. The language considers arrays and null to be "objects" from a typeof perspective, even though they behave very differently from plain objects.
Why This Matters for Type Narrowing
When TypeScript sees typeof x === 'object', it narrows the type to include:
- Plain objects (
{},{ key: value }) - Arrays (
[],[1, 2, 3]) null
This means you can't rely on this check alone if you specifically need a plain object.
Think of It Like Categories
Imagine sorting items into boxes labeled by category. The "object" box is supposed to hold containers, but someone also threw in lists (arrays) and an empty placeholder (null). Now when you reach for something from the "object" box, you can't be sure what you'll get!
Handling the Quirks
To safely narrow to actual objects, you need additional checks beyond just typeof:
if (typeof value === 'object') {
// value could be object, array, or null here!
}
You'll need to combine this with other guards to exclude null and arrays.
Key Takeaway: typeof x === 'object' returns true for plain objects, arrays, AND null, requiring extra checks for precise type narrowing.