- Error
- Reported by the type checker
TS2531
Object is possibly 'null'.
An object that may be null is accessed or called. Check for null first, or use optional chaining.
What it means
With strictNullChecks, a value whose type includes null can't be used as an object until the null case is handled. This form of the message is used when the expression has no simple name to show; with a name, the message is the newer 'x' is possibly 'null'.
Example
declare function find(): { name: string } | null;
export const n = find().name;
ts-r-check -p tsconfig.json --pretty false ts-r outputindex.ts(2,18): error TS2531: Object is possibly 'null'.
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 ?? "". - Change the function so it can't return
null, if that's never meant to happen.