- Error
- Reported by the type checker
TS18048
'{0}' is possibly 'undefined'.
A value that may be `undefined` is used without a check, such as an optional property or parameter. Handle `undefined` first.
What it means
With strictNullChecks, a value whose type includes undefined (an optional property or parameter, a find result, an indexed read under noUncheckedIndexedAccess) can't be dereferenced directly.
Example
interface User {
address?: { city: string };
}
export function city(u: User) {
return u.address.city;
}
ts-r-check -p tsconfig.json --pretty false ts-r outputindex.ts(5,10): error TS18048: 'u.address' 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 it:
if (!u.address) return "";. - Use optional chaining and a default:
u.address?.city ?? "". - If it's always present, make the property required in the type.