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:

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);
});

Leave a Reply