TypeScript Reference ยท Error Codes Worth Knowing
TypeScript errors TS2532 and TS18048: Object is possibly undefined
Reference for TypeScript errors TS2532 and TS18048 (possibly undefined): optional properties, Map.get, find and array indexing, with the idiomatic fixes.
These errors are the undefined counterpart of TS2531. When the type of an expression includes undefined and you read a property, call it or index it, the compiler stops you. TS18048 names the variable ('user' is possibly 'undefined'); TS2532 uses the older generic wording (Object is possibly 'undefined').
undefined enters your types through optional properties and parameters (name?: string), Array.prototype.find, Map.prototype.get, indexing with noUncheckedIndexedAccess, and functions that return early without a value.
const ages = new Map<string, number>(); ages.get("ann").toFixed(); // possibly 'undefined'
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
Source of undefined |
Natural fix |
|---|---|
Optional property a?: T |
a?.b, a check, or a default with ??. |
map.get(key) |
Check the result, or use has() first and handle the miss. |
array.find(...) |
Test for undefined, or use some() when you need a boolean. |
| Optional parameter | Give it a default value in the signature. |
arr[i] with noUncheckedIndexedAccess |
Check bounds, or use arr.at(i) and test the result. |
| Function that can return nothing | Make every path return, or document T | undefined and handle it. |
Edge cases: an optional property typed a?: T accepts undefined explicitly unless exactOptionalPropertyTypes is on. A destructuring default (const { a = 1 } = obj) removes undefined from the type.
Usage notes
- Narrow once, use many times. Assign to a
constand check it; property accesses likeobj.alose narrowing when anything between might changeobj. - Optional chaining short-circuits the whole chain.
a?.b.cstops ataonly; ifbcan be missing too, writea?.b?.c. ??versus||.0and""are valid values;||replaces them with the default,??only replacesnullandundefined.!is a promise to the compiler, not a check. Ifages.get(key)!is wrong, you get a run-timeTypeError.- Assertion functions (
asserts x is T) let you write one helper that throws onundefinedand narrows afterwards. - Definite assignment. A
letvariable that is used before it is certainly assigned reports TS2454 instead.