typescript 访问对象方括号时出现打字错误2532

toiithl6  于 2022-12-24  发布在  TypeScript
关注(0)|答案(1)|浏览(148)

当我尝试检查对象内字段的值时,得到了ts error: Object is possibly 'undefined'.(2532)错误,其中对象的键可以是枚举的值。
下面是重现此问题的一个小示例:

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

在TSPlayground跑步。
当然这只是一个例子,我的代码要复杂得多,我不能通过删除?来改变fruitsInfonumberOfFruits的结构,因为事实是,对象可能不包含所有内容。
我唯一确定的是:我确信,如果某个密钥位于info中,则它也位于fruits

moiiocjp

moiiocjp1#

您的错误是Object is possibly 'undefined'.(2532)
所以你基本上

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

您需要通过!子句将undefined细化为NonNullable或细化为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!")
      }

相关问题