【问题标题】:for..in loop on object with index signature getting error "Element implicitly has an 'any' type because expression of type..."带有索引签名的对象的 for..in 循环出现错误“元素隐式具有'任何'类型,因为类型的表达式......”
【发布时间】:2023-03-27 02:26:01
【问题描述】:

尽管 med 已经定义了索引,但我试图弄清楚为什么 TS 给我一个错误。我确实看到unEquip() 中的slot 被视为字符串,但我不知道如何输入它,也不知道为什么 TS 无法推断类型。

错误:

元素隐含地具有“任何”类型,因为类型的表达式 'string' 不能用于索引类型

代码如下:

type Slot = 'head' | 'body' | 'hands' | 'feet' | 'accessory' | 'mainHand' | 'offHand'

const itemSlots: {
  [key in Slot]: string | null
} = {
  head: null,
  body: null,
  hands: null,
  feet: null,
  accessory: null,
  mainHand: null,
  offHand: null
}

const unEquip = (uuid: string) => {
  for (let slot in itemSlots) {
    if (itemSlots[slot] === uuid) {
      itemSlots[slot] = null
    }
  }
}

也可以在 TS 操场上使用 here

我查看了很多相关的现有 SO 问题,但他们建议使用 any,我认为这不是一个好的答案,来定义索引签名,我已经做过(无济于事)。我关注了this example,但不知何故仍未推断出类型。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    找到答案,使用slot as Slot

    const unEquip = (uuid: string) => {
      for (let slot in itemSlots) {
        if (itemSlots[slot as Slot] === uuid) {
          itemSlots[slot as Slot] = null
        }
      }
    }
    

    基本上,这告诉 TS slotSlot 类型,而不是使用推断的类型。我还是不明白 TS 怎么不能自动推断类型。

    【讨论】:

      猜你喜欢
      • 2018-04-09
      • 2018-09-06
      • 2019-05-12
      • 1970-01-01
      • 2020-04-01
      • 2021-08-16
      • 2017-06-30
      • 2021-08-24
      相关资源
      最近更新 更多