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

Checking for null and undefined

How to safely narrow unknown by checking for null and undefined before accessing properties.

Checking for null and undefined

What you'll learn: How to safely narrow unknown by checking for null and undefined before accessing properties.

The Problem with Unknown Values

When you have a value of type unknown, TypeScript prevents you from doing anything with it—including checking its properties or calling methods. This is good for safety, but you need a way to verify the value isn't null or undefined before working with it.

Think of unknown like a locked box: you can't look inside until you confirm it actually contains something (not null or undefined).

The Simplest Check: Truthiness

The most straightforward way to eliminate null and undefined is a truthiness check:

function processValue(value: unknown) {
  if (value) {
    // value is now: unknown (but not null or undefined)
    // However, you still can't access properties yet!
  }
}

While this narrows out null and undefined, the type remains unknown because other falsy values like 0, "", or false would pass through.

Explicit null and undefined Checks

For precise narrowing, use explicit checks:

function printLength(value: unknown) {
  if (value !== null && value !== undefined) {
    // value is now: {} (the non-nullable unknown)
    // Still need further narrowing to access specific properties
  }
}

The Shorthand: Loose Equality

You can check both null and undefined simultaneously:

function handleValue(value: unknown) {
  if (value != null) {
    // value is neither null nor undefined
    // Now you can continue narrowing with typeof, in, etc.
  }
}

The != null pattern catches both null and undefined because of loose equality rules.

Key Takeaway: Before working with unknown values, explicitly check for null and undefined using !== null && !== undefined or the shorthand != null. This prevents runtime errors, but you'll still need additional type guards to access properties safely.