TS2532: Object is possibly 'undefined'
Similar to "Object is possibly 'null'", but for values TypeScript has inferred could be `undefined` — commonly from optional properties, optional function parameters, or array/Map lookups that don't guarantee an element exists. Narrow with an `if` check or optional chaining before accessing a property, rather than reaching for a non-null assertion by default.
What causes this error
Any type that includes undefined — an optional property (`age?: number`), an optional parameter, or the return type of `Array.prototype.find()`/a `Map.get()` lookup — triggers this check before you can access a property or call a method on it. It's the same underlying mechanism as `Object is possibly 'null'`, just for the `undefined` half of nullish values.
The Fix
const users = [{ id: 1, name: 'Ada' }];
const found = users.find((u) => u.id === 2);
// Wrong — find() can return undefined if nothing matches
console.log(found.name); // TS2532
// Fix 1 — narrow with a check
if (found) {
console.log(found.name);
}
// Fix 2 — optional chaining with a fallback
console.log(found?.name ?? 'Unknown user');Common causes / variations
- `Array.prototype.find()`, `Map.get()`, or similar lookups that can legitimately come back empty
- Reading an optional object property or function parameter without a guard
- Destructuring a value from an API response typed with optional fields
Related errors
See also: Object is possibly 'null', TS7053 Element implicitly has an any type.
Comments
Loading comments...