Fixing TypeScript “Object is possibly ‘undefined'” (TS2532)
TypeScript's error TS2532: Object is possibly 'undefined'. appears when you read a property of a value that might be undefined without checking it first. It often shows up with the result of find on an array, or with an element taken by index like users[0]. Checking that the value is not undefined with if, or deciding what to use when nothing is found with ?. and ??, makes the error go away.
This error catches a runtime bug at the type-checking stage: a search that found nothing, and whose "not found" case was never handled. I reproduced the error in a test environment with both tsc and the language server that editors use, and confirmed the full message and that the fixes remove it.
The test environment was Ubuntu 24.04 with Node.js 22.23.4. I used TypeScript 7.0.2, and for comparison I also ran tsc on the same files with 5.9.3 and 6.0.3. For the editor side, I did not test the editor itself, such as VS Code. Instead, I started the TypeScript language server that editors use for diagnostics (tsc --lsp --stdio) directly and checked its output. I did not test how the error looks in the VS Code UI, or whether it appears inside frameworks such as React.
The full error
In the test environment, I installed TypeScript 7.0.2 in an empty folder and created tsconfig.json with npx tsc --init. The generated tsconfig.json had "strict": true and "noUncheckedIndexedAccess": true.
In src/find.ts, I wrote code that uses find to look up the user with id 3 in an array of users and prints their name:
type User = { id: number; name: string };
const users: User[] = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
];
console.log(users.find((u) => u.id === 3).name);
Running npx tsc --noEmit printed the following (exit code 1). The src folder also contained three other files that I use later, so in reality four errors were printed. Here I show only the one line for src/find.ts.
src/find.ts(8,13): error TS2532: Object is possibly 'undefined'.
With --pretty, the problem location is shown with a squiggly underline. (I removed the color control characters and omitted the output for the other files and the final summary.)
src/find.ts:8:13 - error TS2532: Object is possibly 'undefined'.
8 console.log(users.find((u) => u.id === 3).name);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The message means "that object might be undefined." The underline is not under .name but under users.find((u) => u.id === 3) just before it. In other words, the value that might be undefined is the result of find.
find returns undefined when no element matches the condition (MDN's explanation of Array.prototype.find()). TypeScript also types the return value of find as User | undefined. As described in the strictNullChecks documentation, when this option is enabled, using a value that might be undefined directly is an error. strictNullChecks is included in strict, so this error appears in any project with "strict": true.
The same error appears in the editor
Editors draw red squiggles based on diagnostics (the error position and message) they receive from the TypeScript language server. I started the TypeScript 7.0.2 language server with tsc --lsp --stdio and had it open src/find.ts, using the same steps an editor takes. It returned the diagnostic below. I used a small script I wrote to format the returned JSON as one line per diagnostic (I omitted the hover lines).
server: typescript-go 7.0.2
diagnostics (1):
8:13-8:42 severity=1 source=ts code=2532 Object is possibly 'undefined'.
8:13-8:42 means from column 13 of line 8 up to, but not including, column 42 (the . of .name). This is the same range as the tsc --pretty underline. severity=1 means error, and code=2532 is TS2532. The message text was the same as in tsc.
Storing the result in a variable changes it to TS18048
If you store the result of find in a variable and then use that variable, the error code and message change.
const user = users.find((u) => u.id === 3);
console.log(user.name);
src/find-var.ts(9,13): error TS18048: 'user' is possibly 'undefined'.
Where TS2532 said "Object," this message shows the variable name 'user'. When I put the cursor on user in the language server, the hover showed const user: User | undefined. The same happens with optional properties. For type Config = { db?: { host: string } };, reading config.db.host without a check, where db has a ?, gave a TS18048 that includes the property path: 'config.db' is possibly 'undefined'.
The table below summarizes the errors from the four patterns I tested. TS2532 and TS18048 have the same cause, and the fixes are the same.
| Code | Error |
|---|---|
users.find(...).name |
TS2532: Object is possibly 'undefined'. |
users[0].name |
TS2532: Object is possibly 'undefined'. |
user.name after const user = users.find(...) |
TS18048: 'user' is possibly 'undefined'. |
config.db.host (db is an optional property) |
TS18048: 'config.db' is possibly 'undefined'. |
With TypeScript 5.9.3 and 6.0.3, the same files produced errors with the same codes and messages. However, the exit code of tsc was 2 with 5.9.3 and 6.0.3, and 1 with 7.0.2. If your CI checks the exact exit code value, keep this in mind.
users[0] errors come from noUncheckedIndexedAccess
users[0].name also produced TS2532. Adding undefined to the type of an array element accessed by index comes from the noUncheckedIndexedAccess option. In the tsconfig.json created by tsc --init with TypeScript 7.0.2, this option was true.
When I ran tsc on the same file with --noUncheckedIndexedAccess false, only the error for users[0].name disappeared, and the errors for find and config.db remained. The undefined added to the result of find comes from strictNullChecks, not from noUncheckedIndexedAccess. When I also disabled strictNullChecks, all four errors disappeared. At that point, exactOptionalPropertyTypes in the tsc --init settings could not be set without strictNullChecks and caused TS5052, so I disabled it as well.
Running without the check throws a TypeError
A type error only warns in advance about something that would happen at runtime. When I ran src/find.ts as is with Node.js 22.23.4, it stopped as shown below. (Node.js only strips the type annotations and does not type-check; see Node.js's TypeScript documentation.) The exit code was 1. I replaced the path with a placeholder and omitted the rest of the stack trace.
/path/to/app/src/find.ts:8
console.log(users.find((u) => u.id === 3).name);
^
TypeError: Cannot read properties of undefined (reading 'name')
at Object.<anonymous> (/path/to/app/src/find.ts:8:42)
No user has id 3, so find returns undefined, and reading its .name fails. TS2532 had warned about this before the code ran.
Fixes, and confirming the error is gone
I replaced the file with the fixed version and ran npx tsc --noEmit. It printed nothing and exited with code 0. When I opened the files in the language server, every file returned diagnostics (0):, with no errors.
Check for undefined with if
If you want different handling when nothing is found, split the code with if.
const user = users.find((u) => u.id === 3);
if (user === undefined) {
console.log("id 3 のユーザーはいません");
} else {
console.log(user.name);
}
After the if check, TypeScript narrows the type of user, as described in the official handbook section on equality narrowing. In the hover, user on the if (user === undefined) line was User | undefined, but inside the else branch, user was User. When I ran it, the "not found" message was printed, meaning "there is no user with id 3."
For users[0], I also stored the value in a variable and checked it with if (first), and the error went away. If you only need to go through every element of the array, for (const user of users) does not require any check. In the hover, user was User, and there were no errors.
Use ?. and ?? to choose a fallback value
When a fallback value is fine, for example when you only display something, ?. (optional chaining) and ?? let you write it in one line (TypeScript 3.7 release notes).
console.log(users.find((u) => u.id === 3)?.name ?? "(見つかりません)");
If the value on the left of ?. is undefined or null, ?. returns undefined without reading the rest of the chain. If the left side of ?? is undefined or null, ?? uses the value on the right. When I ran it, the fallback text (the Japanese for "not found") was printed. For the optional property config.db.host, changing it to config.db?.host ?? "localhost" removed the error, and localhost was printed.
If the value should always exist, throw an exception
If data that should always exist is missing, that is a bug in the program. In that case, you can wrap the lookup in a function that throws an exception when nothing is found, so callers do not have to deal with undefined.
function getUser(id: number): User {
const user = users.find((u) => u.id === id);
if (!user) {
throw new Error(`id ${id} のユーザーが見つかりません`);
}
return user;
}
console.log(getUser(2).name);
After the if, return user; runs with user narrowed to User, so it matches the declared return type User. When I ran it, Bob was printed.
Using ! removes the error but still throws at runtime
Adding ! as in find(...)!.name also removes TS2532. Neither tsc nor the language server reported an error.
console.log(users.find((u) => u.id === 3)!.name);
! only tells TypeScript that the value is not undefined. It does not change the runtime behavior (the official handbook section on the non-null assertion operator). When I ran this file, it stopped with the same TypeError: Cannot read properties of undefined (reading 'name') as before the fix. Use ! only when you know the value cannot be undefined.
In the error output when Node.js ran this file, line 8 was shown as console.log(users.find((u) => u.id === 3) .name);, with a blank where the ! had been. ! is a type-only syntax, so Node.js replaces it with a space and removes it before running the code (Node.js's type stripping documentation).





