Course contentsShow
← TypeScript
Lesson 920 of 1,79621. The unknown TypeFree lesson

Narrowing to Object vs Non-Object

How to safely determine if an unknown value is an object before property access.

Narrowing to Object vs Non-Object

What you'll learn: How to safely determine if an unknown value is actually an object before accessing its properties.

The Object vs Non-Object Challenge

When you have an unknown value, you often need to know: is this thing an object that can have properties, or is it a primitive like a string or number? This matters because trying to access properties on primitives will either fail or give you unexpected results.

The tricky part? In JavaScript, typeof null === 'object' — a famous quirk. So you can't just use typeof alone to verify something is a real object.

The Safe Pattern

To narrow unknown to a true object type, you need two checks combined:

function processValue(value: unknown) {
  // Check 1: Is it an object type?
  // Check 2: Is it NOT null?
  if (typeof value === 'object' && value !== null) {
    // TypeScript now knows: value is a non-null object
    // Safe to check for properties
    if ('name' in value) {
      // Further narrowed to objects with 'name' property
    }
  } else {
    // value is a primitive (string, number, boolean, etc.)
    // or null or undefined
  }
}

This two-part check is your gatekeeper: typeof value === 'object' catches objects, arrays, and null, then value !== null excludes the null case, leaving you with genuine objects.

Think of It Like Airport Security

Imagine typeof value === 'object' is the metal detector — it catches most of what you want, but also some false positives (null). The value !== null check is the manual inspection that filters out that one problematic item. Only after both checks can you proceed safely.

Key Takeaway: Always combine typeof value === 'object' && value !== null to safely narrow unknown to a true object type before accessing properties — the typeof check alone will incorrectly include null.