Object is possibly 'null'
An attempt was made to access a property on a value that could be 'null'. This error occurs when the 'strictNullChecks' compiler option is enabled.
- 1Accessing a property on a variable that can be 'null' without checking for 'null' first.
- 2Calling a method on a value that might be 'null'.
- 3A function returns a value that can be 'null', and the caller does not handle that possibility.
Accessing a property on a variable that could be null.
function greet(name: string | null) {
console.log("Hello, " + name.toUpperCase());
}expected output
error TS2531: Object is possibly 'null'.
Fix 1
Add a null check
WHEN The value can legitimately be null.
function greet(name: string | null) {
if (name !== null) {
console.log("Hello, " + name.toUpperCase());
}
}Why this works
A conditional check ensures the property is accessed only when the object is not null.
Fix 2
Use optional chaining
WHEN You want to access a property safely.
function greet(name: string | null) {
console.log("Hello, " + name?.toUpperCase());
}Why this works
The optional chaining operator (?.) safely accesses the property and returns 'undefined' if the object is null or undefined.
✕ Use the non-null assertion operator (!)
This tells TypeScript to ignore the possibility of null, which can lead to a runtime 'Cannot read properties of null' error if the value is indeed null.
microsoft/TypeScript src/compiler/diagnosticMessages.json
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev