Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I handle typescript nested objects being possibly undefined

I have an object of objects that I’ve defined type aliases for and am trying to map through it but I’m stuck as how to handle the following error:

Cannot invoke an object which is possibly ‘undefined’.

Here is my use case:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type apple = {
  color: string
  size: string
}
type apples = {
  [x: string]: apple
}

const appleObj: apples = {
  1: {
    color: "red",
    size: "small",
  },
  2: {
    color: "green",
    size: "large",
  },
}

appleObj.map(({ color, size }) => {
  console.log(color, size)
})

Please help 🙂

>Solution :

You can’t use map on object directly, we need to use Object.keys to map the object as below.

Object.keys(appleObj).map(key => {
    const apple = appleObj[key];
    console.log(apple.color, apple.size);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading