- Error
- Reported by the type checker
TS2532
Object is possibly 'undefined'.
An object that may be undefined is accessed or called. Check for undefined first, or use optional chaining.
What it means
With strictNullChecks, a value whose type includes undefined can't be used as an object until the undefined case is handled. This form is used when the expression has no simple name to show; with a name, the message is 'x' is possibly 'undefined'.
Example
declare function find(): { name: string } | undefined;
export const n = find().name;
ts-r-check -p tsconfig.json --pretty false ts-r outputindex.ts(2,18): error TS2532: Object is possibly 'undefined'.
Recorded by node scripts/verify-examples.mjs with ts-r built from commit 6deaf01. The example uses the default tsconfig: strict, target: es2022, module: esnext, moduleResolution: bundler.
How to fix
- Check first:
const r = find(); if (r) { r.name }. - Use optional chaining and a default:
find()?.name ?? "".