Skip to main content
TypeScript & Node.js · Developer Error Resolution Lab

Fix TypeScript Error TS2532: 'Object is possibly undefined' (or 'null')

Safely handle optional types using optional chaining (?.) and nullish coalescing (??) operators.

Triggered Error Message:

error TS2532: Object is possibly 'undefined'. (or TS18048)

Customize Solution for Your Environment
// 1. Optional chaining (?.) with nullish coalescing (??):
const count = data?.items?.length ?? 0;

// 2. Early return guard clause (Type Narrowing):
if (!data || !data.items) {
  return null; // TS automatically narrows type after this check
}

// 3. Non-null assertion (!) - ONLY use if 100% sure value is set:
const val = data!.items;

Root Cause & Mechanism Analysis

Why does this error occur?

Strict null checks (`strictNullChecks: true`) detected access to a property or method on a variable whose type union includes `undefined` or `null`.

Frequently Asked Questions

What is the difference between ?? and || in JavaScript?
`??` only falls back on `null` or `undefined`. `||` falls back on any falsy value including `0`, `""`, and `false`.
Browse All 35 Guides