【发布时间】: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