Array.find object is possibly defined in TypeScript
In this tutorial, we are going to learn about how to solve the Array.find() object is possibly defined error in TypeScript.
The Array.find()
object is possibly undefined error occurs if we don’t provide any fallback value to the object property or doesn’t return anything from the find() method, it will show the following error in the console.
Example:
const arr = [
{ a: 1, name: "Raju" },
{ b: 2, name: "John" },
];
const result = arr.find((el) => {
return el.a === 1;
});
result.name.toLowerCase();
Output:
Object is possibly 'undefined'.
In the above code, we are accessing the result.name
property which is not available untill it runs the arr.find()
method, so by any chance if name
property is not available in the object (eg: backend data is not available) we should provide some default value to handle it.
To solve the error, we can use the optional chaining (?) operator in TypeScript.
Here is an example:
const arr = [
{ a: 1, name: "Raju" },
{ b: 2, name: "John" },
];
const result = arr.find((el) => {
return el.a === 1;
});
result?.name.toLowerCase();
In the example above, we have used the optional chaining operator ?
. So it checks implicitly if result
is not null or undefined before it access to the result.name
, if result
is null or undefined, the expression short-circuts and returns undefined
.
Alternatively, we can solve this error using if
conditional check in TypeScript.
const arr = [
{ a: 1, name: "Raju" },
{ b: 2, name: "John" },
];
const result = arr.find((el) => {
return el.a === 1;
});
if (result != undefined){
console.log(result.name.toLowerCase()); // "raju"
}