typescript - 带有索引签名的对象的 for..in 循环出现错误“元素隐式具有'任何'类型,因为类型的表达式......”
问题描述
我试图弄清楚为什么尽管 med 定义了索引,但 TS 还是给了我一个错误。我确实看到slot
inunEquip()
被视为字符串,但我不知道如何键入它,或者为什么 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
,我认为这不是一个好的答案,或者定义我已经完成的索引签名(无济于事)。我遵循了这个例子,但不知何故仍未推断出类型。
解决方案
找到答案,使用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 如何不能自动推断类型。
推荐阅读
- javascript - 如何使用淘汰赛仅更新下拉列表
- asp.net-mvc - Bootstrap 4不能垂直居中行div
- html - SVG 文本选择在 Chrome 中不起作用吗?
- javascript - 移入阵列时产生无限循环
- xpath - Xpath 选择所有以下兄弟姐妹以及匹配的元素
- css - 使用grails时如何在gsp中对齐部分中的元素
- ssis - SSIS 计划并重新启动包执行
- javascript - 用于跳过元素的 querySelector
- arrays - 更新 AngularFire2 中的嵌套数组
- python-2.x - 打印后使用 raw_input,未按正确顺序执行