TS2531
TypeScriptERRORCriticalType SystemHIGH confidence

Object is possibly 'null'

What this means

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.

Why it happens
  1. 1Accessing a property on a variable that can be 'null' without checking for 'null' first.
  2. 2Calling a method on a value that might be 'null'.
  3. 3A function returns a value that can be 'null', and the caller does not handle that possibility.
How to reproduce

Accessing a property on a variable that could be null.

trigger — this will error
trigger — this will error
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.

Add a null check
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.

Use optional chaining
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.

What not to do

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.

Sources
Official documentation ↗

microsoft/TypeScript src/compiler/diagnosticMessages.json

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All TypeScript errors