Author -  Sai gowtham

Solve - Object is possibly defined error in TypeScript

In this tutorial, we are going to learn about how to solve the Object is possibly defined error in TypeScript.

If we don’t provide any fallback value to the object property in TypeScript, it will show the following compile time 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.

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"
}

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY