TypeScript TS2532: Object is possibly 'undefined'
TS2532 means strict null checks cannot prove a value exists before reading through it. Guard it, add optional chaining, or narrow the type at the source.

Introduction & Quick Summary
tsc stops the build with this line, usually on a chain of property access that ran fine before strict mode:
src/orders.ts:24:32 - error TS2532: Object is possibly 'undefined'.
24 return order.customer.address.city;
~~~~~~~Quick answer: with strictNullChecks enabled, TypeScript types a value as T | undefined and refuses to read through it until your code proves the value exists. Either guard the value, or make the missing case explicit with ?. and ??, or remove undefined from the type when the design guarantees it is there.
type Order = { customer?: { address?: { city?: string } } };
// guarded: every optional link handled
function city(order: Order): string {
return order.customer?.address?.city ?? "unknown";
}
// or fail loudly at the boundary instead of scattering `!`
function requireCity(order: Order): string {
const value = order.customer?.address?.city;
if (value === undefined) throw new Error("order has no city");
return value;
}The error says the type system lost the guarantee, not that the runtime value is broken. Every fix is about narrowing — proving the value is not undefined before the access — and the interesting cases are where narrowing is lost: callbacks, index access, Map.get, and values that arrive from JSON.parse.
Core Mechanics, Signatures & Reproducible Setup
The error exists because of one compiler flag. strictNullChecks gives undefined and null their own types instead of letting them flow into everything.
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"target": "ES2022",
"module": "nodenext",
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true
},
"include": ["src"]
}strict turns on strictNullChecks plus seven related checks, so most projects meet TS2532 the day they enable it. A five-line reproduction needs nothing else:
// src/repro.ts
type User = { name?: string };
const user: User = {};
console.log(user.name.toUpperCase());npx tsc --strict --noEmit src/repro.ts
# src/repro.ts:4:13 - error TS18048: 'user.name' is possibly 'undefined'.Note the code: newer compilers report some of these accesses as TS18048 ('x' is possibly 'undefined') and TS2532 for member access through a possibly-undefined object (order.customer.address). The cause, the settings and the fixes are identical, so treat both as one class of error.
Narrowing is the mechanism that removes it. TypeScript follows control flow through a function body and refines a union at each test: if (x !== undefined) narrows in the true branch, if (!x) narrows both branches but also rejects 0, "" and false, x?.y short-circuits to T | undefined, x ?? fallback strips null and undefined, and x! strips them with no runtime check at all. An assignment, an await, or a callback boundary can reset what the compiler knows.
Key Comparison Table
| Fix | Runtime behaviour | Type afterwards | When it is right |
|---|---|---|---|
if (x !== undefined) guard | none | T in the guarded branch | missing value is exceptional |
x?.y optional chain | returns undefined | T or undefined | missing value is normal |
x ?? fallback | substitutes default | T or fallback type | a sensible default exists |
x! non-null assertion | none, unsafe | T | invariant proven elsewhere |
| default parameter / destructuring | substitutes default | T | optional input with a default |
| Access pattern | Type before the error | Code | Preferred narrowing |
|---|---|---|---|
optional property chain a.b.c | B or undefined | TS2532 | a.b?.c |
array element rows[i] | Row or undefined | TS18048 | store in const, guard, return |
Map.get(key) | V or undefined | TS18048 | guard the stored result |
find() result | T or undefined | TS18048 | early return |
| destructured optional property | T or undefined | TS2532 | default in the pattern |
| Sibling error | Meaning | Difference from TS2532 |
|---|---|---|
| TS2531 | Object is possibly null | the union member is null, not undefined |
| TS18048 | 'x' is possibly 'undefined' | newer wording for the identifier form |
| TS2722 | Cannot invoke an object which is possibly undefined | calling, not reading |
| TS2322 | type not assignable | assignment failure, not an access |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Optional chains that stop too early
The most common misread of the error is putting ?. on the wrong link: a?.b.c still dereferences b unconditionally, and the chain has to reach the last optional step.
type Config = { db?: { host: string } };
function host(cfg: Config): string {
return cfg.db?.host.toUpperCase() ?? "localhost";
}The ?? is what satisfies a string return type; without it the expression is string | undefined and the next call on it fails with TS18048.
2. Index access and noUncheckedIndexedAccess
By default an array lookup is typed T, which is unsound and hides this class of error until runtime. Turn the flag on and the compiler starts asking:
const rows: string[] = [];
// with noUncheckedIndexedAccess: string | undefined
const row = rows[0];
if (row === undefined) throw new Error("empty result set");
console.log(row.trim()); // narrowed to stringUse for...of where the loop guarantees an element, and a guard plus early return in index-driven code. Lookups on Record<string, T> behave the same way.
3. Narrowing lost across callbacks and await
Any function boundary invalidates a narrowing, and the compiler is right to complain:
type Cache = { value?: string };
function write(cache: Cache, log: (s: string) => void) {
const value = cache.value;
if (value === undefined) return;
setTimeout(() => log(value.toUpperCase()), 10); // const survives the closure
}Copy to a const before the closure: it satisfies the compiler and protects you when the property changes underneath. The same rule applies after await — a property read before the suspension can be different after it, because another task may have mutated the object.
4. Narrowing through your own functions
A boolean helper narrows nothing unless you declare it as a type predicate:
function isPresent<T>(value: T | undefined | null): value is T {
return value !== undefined && value !== null;
}
const maybe: string | undefined = process.env.HOME;
if (isPresent(maybe)) {
maybe.length; // string
}Use the same technique for domain checks (isSuccess(result)), so the guard is written once and narrows at every call site.
5. Map.get, find, and dictionary lookups
Map.get returns V | undefined even when the same key was just checked, because the two lookups are independent calls into a mutable collection:
const sessions = new Map<string, { userId: string }>();
const session = sessions.get(token);
if (session === undefined) return null;
return session.userId; // narrowed
// or one lookup with a default instead of has() + get()!
return (sessions.get(token) ?? { userId: "guest" }).userId;Array.prototype.find and Object.fromEntries results have the same shape: store the result, then guard it.
6. Destructuring defaults and exactOptionalPropertyTypes
A default in a destructuring pattern removes undefined from the binding, which is often the cleanest fix inside a handler or component:
type Props = { title?: string; limit?: number };
function render({ title = "untitled", limit = 20 }: Props) {
return `${title} (${limit})`;
}With exactOptionalPropertyTypes on, { title: undefined } is no longer assignable to title?: string, so an explicit undefined from an API response must be normalized before it reaches the type. Inspecting the payload is faster with the JSON formatter; after a refactor that made a field optional, the text diff tool shows exactly which field changed.
Common Compilation/Runtime Mistakes & Version Gotchas
- Sprinkling
!to silence the error. The assertion removesundefinedfrom the type and adds no runtime check; the crash simply moves to production. Use it only where an invariant is enforced elsewhere. if (x)instead ofif (x !== undefined). Falsy narrowing also rejects0,""andfalse, which then produces wrong fallbacks in numeric and boolean code.== nullversus=== undefined. Loose equality catches bothnullandundefined; choose it deliberately and keep it consistent with the declared type.- Assuming narrowing survives a callback. Closures,
awaitand generator bodies reset flow analysis; copy toconstfirst. - Turning the flag off instead of fixing types. Disabling
strictNullCheckssilences every related error at once and reintroduces null crashes across the codebase. - Version notes.
stricthas includedstrictNullCheckssince TypeScript 2.0;exactOptionalPropertyTypesandnoUncheckedIndexedAccessare separate flags that change types only, not runtime behaviour, so enable them in their own branch. Newer compilers printTS18048where older ones printedTS2532; yourtypescriptversion decides the code, not the semantics.
Official documentation: strictNullChecks and Narrowing.
Official references
primary documentationThe TypeScript documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related TypeScript guides
All TypeScript guidesTypeScript TS2349: This expression is not callable
TS2349 means the value has no call signature at that point. Narrow unions, fix module default imports and guard optional calls instead of asserting.
TypeScript: Cannot find name 'process' with @types/node
TS2304 on process or Buffer means the compiler has no Node declarations. Install @types/node, stop excluding it, and align its version to the runtime.
TypeScript TS18046: 'e' is of type 'unknown'
TS18046 comes from useUnknownInCatchVariables: a caught error is unknown, not any. Narrow it with instanceof or a type guard before reading message.
TypeScript TS2339: Property does not exist on type
TS2339 means the declared type has no such member. Declare the shape, narrow unions and guard unknown values instead of casting at the read.
More in TypeScript
All TypeScript guidesThe guides filed next to this one in TypeScript, in library order.