TS2532
TypeScriptERRORCriticalType SystemHIGH confidence

Object is possibly 'undefined'

What this means

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.

Why it happens
  1. 1Accessing a property on an optional property of an object without checking if it exists.
  2. 2Using an element from an array that might not exist at that index.
  3. 3A function returns a value that can be 'undefined', and the caller does not handle that possibility.
How to reproduce

Accessing an optional property without checking for its existence.

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

Add an undefined check
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.

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

What not to do

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.

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