The Object is possibly ‘undefined’ occurs when we try to access a property of an object that is undefined
. Sometimes few properties in TypeScript can be defined as optional and it may lead to this error.
In this article, we will look at what is Object is possibly ‘undefined’ error in TypeScript and how to resolve this error with examples.
What is Object is possibly ‘undefined’ error in TypeScript?
As the error itself suggests that some of the property in the Object is undefined
or you have made that as an optional in the TypeScript.
Let us reproduce this issue with a simple example.
type Book = {
genre?: {
language?: string;
author?: string;
};
};
const b1: Book = {};
// Now if language is optional and not defined.
p1.genre.language;
Output
// Error: Object is possibly 'undefined'.ts(2532)
How to fix Object is possibly ‘undefined’ error in TypeScript
There are several ways to fix the error. Let us explore the best approaches to avoid this issue.
Solution 1: Using Optional chaining
The Optional chaining refers to the question mark dot (?.
) in Typescript. It is used while accessing a nested property of an object.
The ?.
operator is like the .
chaining operator, except that instead of causing an error if a reference is nullish (null
or undefined
), the expression short-circuits with a return value of undefined
.
We can use this even with function calls and instead of throwing error it returns undefined
if the given function does not exist.
After using the optional chain operator, it will not throw any error but the return value will be undefined
as shown in the below example.
type Book = {
genre?: {
language?: string;
author?: string;
};
};
const b1: Book = {};
// Now, if language is optional and not defined.
const resultVal = b1?.genre?.language;
console.log(resultVal)
Output
undefined
*Fact Check: This approach is used in remote method invocation or API to read data.
Solution 2: Checking undefined
One of the easiest ways of checking the value for correctness is before assessing the property. There are multiple ways to do this. Let us discuss them.
A). Using if
type Book = {
genre?: {
language?: string;
author?: string;
};
};
const b1: Book = {};
if (b1.genre != undefined) {
console.log(b1.genre.language?.toUpperCase);
console.log(b1.address.author?.toUpperCase);
}
This method is self-explanatory as we check the value before performing any operation.
B). Using non-null assertion
We use it when we are convinced that the property value cannot be null. It can be undefined but not null.
type Book = {
genre?: {
language?: string;
author?: string;
};
};
const b1: Book = {
genre: {
language: 'English',
author: 'Shakespeare',
},
};
console.log(b1.genre!.language); // English
Solution 3: Using the AND / OR logical operator
This is similar to providing fallback value. In case we find the value as undefined no error is thrown. Instead, it returns the fallback value.
validateBook(book || 'default-Book');
type Book = {
genre?: {
language?: string;
author?: string;
};
};
const b1: Book = {};
if (b1.genre && b1.genre.language) {
console.log(b1.genre.language);
}
Here, we have shown this by calling a function called validateBook and passing a reference to the book. If the value returned is undefined
, default-Book will be returned instead of an error.
Difference between ||
and ??
The main difference is:
||
returns the first true value.??
returns the first defined value.
In other words, ||
does not differentiate between false, 0, an empty string, and null/undefined. They are all falsy
values. If the first argument of ||
is a false value, we’ll get the second argument as the output.
Solution 4: Using ?? nullish coalescing operator
The nullish coalescing operator is used as two question marks ??
.
The nullish coalescing operator (??
) is a logical operator that returns its right-hand side operand when its left-hand side operand is null
or undefined
, and otherwise returns its left-hand side operand.
As it treats null
and undefined
likewise, we declare that an expression is “defined” when it’s neither null
nor undefined
. In other words, it returns the first parameter if it’s not null/undefined. else, the second one.
The result of x ?? y
is:
- if
x
is defined, thenx
, - if x isn’t defined, then
y
.
// Example in case of null
const foo = null ?? 'default string';
console.log(foo);
// Example in case of undefined
const bar = undefined ?? 'My default value';
console.log(bar);
// Example in case of function
function initializeAudio() {
let volume = localStorage.volume || 0.5;
console.log(volume)
}
initializeAudio();
Output
default string
My default value
0.5
Conclusion
We can safely assume that type check is the best way to stop the Object is possibly ‘undefined’ error from occurring. Instead of comparing to undefined
, we can use the optional chaining, nullish coalescing, AND, OR operators. Among them, it is better to go with the nullish coalescing operator as it is more efficient.