🔧 Error Fixes
· 1 min read
Last updated on

TypeScript: Object Is Possibly 'undefined' — How to Fix It


TS2532: Object is possibly 'undefined'.
TS18048: 'user' is possibly 'undefined'.
TS2533: Object is possibly 'null' or 'undefined'.

TypeScript is telling you a value might be undefined or null, and you’re using it as if it definitely exists.

Fix 1: Optional chaining (?.)

// ❌ user might be undefined
const name = user.name;

// ✅ Returns undefined instead of crashing
const name = user?.name;
const city = user?.address?.city;

Fix 2: Nullish coalescing (??) for defaults

// ✅ Provide a fallback value
const name = user?.name ?? 'Anonymous';
const port = config?.port ?? 3000;

Fix 3: Type guard (if check)

// ✅ TypeScript narrows the type after the check
if (user) {
  console.log(user.name);  // TypeScript knows user exists here
}

// ✅ Also works with return
if (!user) return;
console.log(user.name);  // Safe after early return

Fix 4: Non-null assertion (!) — use sparingly

// ✅ Tells TypeScript "I know this exists"
const name = user!.name;

⚠️ Only use this when you’re 100% sure the value exists. If you’re wrong, it crashes at runtime. Prefer optional chaining or type guards.

Fix 5: Fix the type definition

Sometimes the type is wrong — the value is always defined but the type says it might not be:

// If you know the array always has items
const items: string[] = getItems();
const first = items[0];  // TS2532: possibly undefined

// ✅ Use a type assertion if you're sure
const first = items[0] as string;

// ✅ Or check first (safer)
const first = items.length > 0 ? items[0] : 'default';

Fix 6: With document.getElementById

// ❌ getElementById returns HTMLElement | null
const btn = document.getElementById('submit');
btn.addEventListener('click', ...);  // Object is possibly null!

// ✅ Check first
const btn = document.getElementById('submit');
if (btn) {
  btn.addEventListener('click', ...);
}

// ✅ Or assert (if you know it exists)
const btn = document.getElementById('submit')!;