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')!;
Related resources
Related: What is TypeScript