Quick Solution – “Object is possibly ‘undefined’” in TypeScript

“Object is possibly ‘undefined’” in TypeScript

Whenever you are working on typescript, you may get exceptions, depending on the project you are working on. The “Object is possibly ‘undefined’” in TypeScript is an error warning that you get when trying to access an object’s property, which is not defined. In TypeScript, a few properties are defined as optional that can show up the error warning.

Let’s discuss how to fix it

How to fix “Object is possibly ‘undefined’” in TypeScript

There are a few successful solutions to get rid of this error warning, but before that, let’s have a look at how error occurs:

type Book1 = {
  genre?: { 
    language?: string;
    author?: string;
  };
};

const b: Book1 = {};

// If language is undefined.
b.genre.language;

Output

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

Solution 1 – Error “Object is possibly ‘undefined’” because Optional Chaining

Referring to the question mark dot (?.) in TypeScript is optional chaining that works when it comes to accessing a property’s nested property. The chain operator shows an error warning if the reference is undefined or null. In that case, the expressions return an undefined value. Take a look at the example

type Book1 = {
  genre?: { 
    language?: string;
    author?: string;
  };
};

const b: Book1 = {};
// If language is undefined.
const val = b?.genre?.language;
console.log(val)

Output

undefined

Solution 2 – Check for Correctness

The simplest and easiest way to solve the error is to check the values for correctness before you try to access the property. Let’s check out the ways

Using non-null assertion

This is the way that can only be used when you know that the value of the property is not null. Look at the example

type Book1 = {
  genre?: { 
    language?: string;
    author?: string;
  };
};

const b: Book1 = {
  genre: {
    language: 'English',
    author: 'Shakespeare',
  },
};

console.log(b.genre!.language);

Output

English

Using if

Here, we check the value before we perform any operation, and that’s the reason it is called the self-explanatory method.

type Book1 = {
  genre?: { 
    language?: string;
    author?: string;
  };
};

const b: Book1 = {};
if (b.genre != undefined) {
  console.log(b.genre.language?.toUpperCase);
  console.log(b.address.author?.toUpperCase);
}

Solution 3 – OR/AND Operator

In this solution, you get the fallback value in return even if the value is undefined, it shows no error. Let’s have an example of calling a validateBook function along with passing a reference to the book

validateBook(book || 'default-Book');

type Book1 = {
  genre?: { 
    language?: string;
    author?: string;
  };
};

const b: Book1 = {};
if (b.genre && b.genre.language) {
  console.log(b.genre.language);
}

We use ‘||’ to get the first values as True in return. The ?? returns the first values as defined. 

Solution 4 – the nullish coalescing operator (??)

The double (??) is known as the nullish coalescing operator, which returns the operand of the right side when the operand on the left side is undefined or null, or else it returns the operand of the left side. You will get the first parameter in return if it is not undefined or null, otherwise, it returns the second.  Let’s take an example

Suppose, x ?? y is

  1. If x is not defined, then y
  2. If x is defined, then x
// null case
const result1 = null ?? 'result1';
console.log(result1);

// Undefined case
const result2 = undefined ?? 'result2';
console.log(result2);

// Function case
function calcValue() {
  let result3 = localValue.value || 0.8;
  console.log(result3)
}

calcValue();

Output

result1
result2
0.8

Conclusion

All the solutions discussed can help you get rid of “Object is possibly ‘undefined’” in TypeScript.  I hope you find it helpful!

Leave a Reply

Your email address will not be published. Required fields are marked *