Home > OS >  typescript error 2532 with object square brackets access
typescript error 2532 with object square brackets access

Time:12-21

I got the ts error: Object is possibly 'undefined'.(2532) error when I attempt to check the value of a field inside an object, where the key of the object can be a value of an Enum.

Here is a small example to reproduce this issue:


enum Fruits {
   Apple = "Apple",
   Bannana = "Bannana",
   // and a lot more…
}

type fruitsInfo = {
  [key in Fruits]? : { cal: number, carb: number, }
};

type numberOfFruits = {
  [key in Fruits]? : number
};

function makeMeal(info : fruitsInfo, fruits : numberOfFruits) {
   for (const keyStr in info) {
      const key = keyStr as Fruits;
      if (fruits[key] > 2) {
         console.log("You eat a lot!")
      }
   }
}

Run on TS Playground.

Of course this is an example, my code is quite more complicated. I cannot change the structure of fruitsInfo nor numberOfFruits by removing the ?, because the fact is, the object may not contain everything.

The one thing I know for sure is: I am sure that if a key is in info, it is in fruits

CodePudding user response:

Your error is literally Object is possibly 'undefined'.(2532)

So you basically have

      if (undefined > 2) { // <! The value 'undefined' cannot be used here.(18050)
         console.log("You eat a lot!")
      }

You need to either refine undefined to NonNullable via ! clause or to number

      if (fruits[key]! > 2) { // say that it's not `undefined`
         console.log("You eat a lot!")
      }      
      if (Number(fruits[key]) > 2) { // convert it to number (NaN)
         console.log("You eat a lot!")
      }
  • Related