TS2532: Object is possibly 'undefined'
What’s happening?
Section titled “What’s happening?”This error occurs when you try to access a property or call a method on an object that might be undefined.
With strictNullChecks enabled, TypeScript prevents property access on potentially undefined values.
Reproduction
Section titled “Reproduction”interface User { name: string; email: string;}
function getUser(): User | undefined { return Math.random() > 0.5 ? { name: "Alice", email: "alice@example.com" } : undefined;}
const user = getUser();console.log(user.name);// ❌ Object is possibly 'undefined'getUser() can return undefined, but we’re accessing .name without checking.
Why does TypeScript complain?
Section titled “Why does TypeScript complain?”TypeScript considers these possibilities:
{ name: "Alice", ... }→.nameworks ✅undefined→.namecrashes ❌
Because the second case is possible, TypeScript rejects the unsafe property access.
Solutions
Section titled “Solutions”Option 1: Optional chaining (recommended)
Section titled “Option 1: Optional chaining (recommended)”const user = getUser();console.log(user?.name); // ✅ Returns 'Alice' or undefinedWhen to use:
- ✅ Safest and most concise
- ✅ Returns
undefinedinstead of throwing - ✅ Can chain multiple levels:
user?.profile?.avatar?.url
Option 2: Type narrowing with a check
Section titled “Option 2: Type narrowing with a check”const user = getUser();if (user !== undefined) { console.log(user.name); // ✅ TypeScript knows user is defined}When to use:
- ✅ When you need to perform multiple operations on the object
- ✅ Better for complex logic inside the block
Option 3: Provide a default value
Section titled “Option 3: Provide a default value”const user = getUser();console.log(user?.name ?? "Guest"); // ✅ Falls back to "Guest"When to use:
- ✅ When you have a sensible default
- ✅ Common in UI rendering
Option 4: Non-null assertion (use sparingly)
Section titled “Option 4: Non-null assertion (use sparingly)”const user = getUser();console.log(user!.name); // ⚠️When to use:
- ⚠️ Only when you’re absolutely certain the value exists
- ⚠️ Can cause runtime errors if you’re wrong
Common scenarios
Section titled “Common scenarios”API responses
Section titled “API responses”const response = await fetch('/api/user');const data = await response.json();console.log(data.user.name);// ❌ Object is possibly 'undefined'
// ✅ Fix:console.log(data?.user?.name ?? "Unknown");Array find method
Section titled “Array find method”const users = [{ id: 1, name: "Alice" }];const user = users.find(u => u.id === 2);console.log(user.name);// ❌ Object is possibly 'undefined'
// ✅ Fix:const user = users.find(u => u.id === 2);if (user) { console.log(user.name);}Optional props in React
Section titled “Optional props in React”interface Props { user?: User;}
function UserProfile({ user }: Props) { return <div>{user.name}</div>; // ❌ Object is possibly 'undefined'
// ✅ Fix: return <div>{user?.name ?? "Guest"}</div>;}Key takeaways
Section titled “Key takeaways”- Use optional chaining (
?.) as your first choice - Combine with nullish coalescing (
??) for defaults - Type narrowing is best for complex multi-step logic
- Avoid non-null assertions unless absolutely necessary