首页 > 解决方案 > 带有索引签名的对象的 for..in 循环出现错误“元素隐式具有'任何'类型,因为类型的表达式......”

问题描述

我试图弄清楚为什么尽管 med 定义了索引,但 TS 还是给了我一个错误。我确实看到slotinunEquip()被视为字符串,但我不知道如何键入它,或者为什么 TS 无法推断类型。

错误:

元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型

这是代码:

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 操场上找到。

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

标签: typescript

解决方案


找到答案,使用slot as Slot

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

基本上,这告诉 TSslot是类型Slot而不是使用推断的类型。我仍然不明白 TS 如何不能自动推断类型。


推荐阅读