Object is possibly 'undefined'
An attempt was made to access a property on a value that could be 'undefined'. This error occurs when the 'strictNullChecks' compiler option is enabled.
- 1Accessing a property on an optional property of an object without checking if it exists.
- 2Using an element from an array that might not exist at that index.
- 3A function returns a value that can be 'undefined', and the caller does not handle that possibility.
Accessing an optional property without checking for its existence.
interface User {
name?: string;
}
function greet(user: User) {
console.log("Hello, " + user.name.toUpperCase());
}expected output
error TS2532: Object is possibly 'undefined'.
Fix 1
Add an undefined check
WHEN The value can be undefined.
interface User {
name?: string;
}
function greet(user: User) {
if (user.name) {
console.log("Hello, " + user.name.toUpperCase());
}
}Why this works
A 'truthiness' check ensures the property exists and is not an empty string before being used.
Fix 2
Use optional chaining
WHEN You want to safely access a potentially undefined property.
interface User {
name?: string;
}
function greet(user: User) {
console.log("Hello, " + user.name?.toUpperCase());
}Why this works
The optional chaining operator (?.) will stop the expression and return 'undefined' if 'user.name' is undefined.
✕ Use the non-null assertion operator (!)
This asserts that the value is neither null nor undefined, which can cause a runtime error if the assumption is wrong.
microsoft/TypeScript src/compiler/diagnosticMessages.json
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev