ts object is possibly ‘undefined’ – How to Fix Object is possibly ‘undefined’ error in TypeScript

ts object is possibly ‘undefined’: When we try to access a property on an object that may be undefined, we get the “Object is possibly ‘undefined'” error (example- marked as optional).

To fix the mistake, use optional chaining to short-circuit if the reference is null, such as e?.name?.salary.

index.ts

// Create a class
type Employ = {
  //  Create a nested objects which may be undefined 
  name?: { 
    address?: string;
    salary?: string;
  };
};
// creating an object for the above employ class
const e: Employ = {};

// When we try to get salary then we get => Error: Object is possibly 'undefined'.ts(2532)
e.name.salary;

Output:

Error: Object is possibly 'undefined'.ts(2532)

The nameproperty on the Employ type is marked as optional, so it may be undefined.

This is why we cannot safely access `address` or salaryproperties.

Fixing Object is possibly ‘undefined’ error in TypeScript

We can fix this error by using theoptional chaining (.) operator.

Method #1: Using Optional Chaining

// Create a class
type Employ = {
// Create a nested objects which may be undefined 
  name?: {
    address?: string;
    salary?: string;
  };
};
// creating an object for the above employ clas
const e: Employ = {};

// Here now we don't get any error.It works fine
const rslt = e?.name?.salary;

Explanation:

There will be NO errors in this case.

In TypeScript, the dot (?.) syntax is known as optional chaining. It is similar to using dot notation to access a nested property of an object, but instead of throwing an error if the reference is nullish (null or undefined), it short-circuits and returns undefined.

This method is typically used for retrieving data from a remote API or reading it from a file, where some of the 
properties may be empty.

Method #2: Using If Conditional Statement

Object is possibly ‘undefined’: We used an if statement to determine whether the e.name property is not equal to undefined or null.

// Create a class
type Employ = {
//  Create a nested objects which may be undefined 
  name?: {
    address?: string;
    salary?: string;
  };
};
// creating an object for the above employ class
const e: Employ = {};

// check if the name property of the employ class is not undefined using the optional chaining(.) and if conditional statement
if (e.name != undefined) {
  console.log(e.name.address?.toUpperCase);
  console.log(e.name.salary?.toUpperCase);
}

Explanation:

There will be NO errors in this case.

TypeScript knows that the e.nameis of type object and not undefined once we enter the if block.

Here we utilized loose not equals (!=) to check for both undefined and null values. You can only use strict not equals (!==) to check for undefined.

Because undefined is identical to null in a loose comparison, it covers both undefined and null.

console.log(undefined == null);  // output => true
console.log(undefined === null); // output => false

Output:

true
false

If you are certain that the property cannot have a null value, you can use the non-null assertion operator.

//  Create a class
type Employ = {
  name?: {
    address?: string;
    salary?: string;
  };
};

const e: Employ = {
  name: {
    address: 'Hyderabad',
    salary: '50000',
  },
};

console.log(e.name!.address); 
console.log(e.name!.salary);

Output:

Hyderabad
50000
  • In TypeScript, the exclamation mark(!) is the non-null assertion operator.
  • It removes null and undefined values from a type without performing any explicit type checking.
  • When you use this method, TypeScript is basically told that this value will never be null or undefined.
  • We used it right after the name property, so TypeScript knows that e.name will never be null or undefined

Method #3: Using Logical AND(&&) Operator

When comparing properties in an if statement, utilize the logical AND (&&) operator to ensure that the property is of the correct type.

// @@@

type Employ = {
  name?: {
    address?: string;
    salary?: number;
  };
};

const e: Employ = {};

if (
  e?.name &&
  typeof e.name.salary === 'string' &&
  e.name.salary > 1000
) {
  console.log('success');
}

Output:

Your program did not output anything!

Explanation:

Here the logical AND (&&) operator ensures that the property name is not undefined, that salary exists on the object and is a number before comparing it to the number 1000.

This is required because if the reference is nullish (null or undefined), the optional chaining operator (?.) would return undefined, and TypeScript does not support comparing undefined to a string.