我有以下对象
const CHARACTER_ITEMS = {
ITEM_ARMS_LIGHT: "",
ITEM_LEGS_LIGHT: "",
ITEM_ARMS_HEAVY: "",
ITEM_LEGS_HEAVY: ""
}
然后我想以动态方式访问这个对象的一些值,即
const variant = 'HEAVY'; // This is dynamic, based on server response
const arms = CHARACTER_ITEMS[`ITEM_LEGS_${variant}`]
不幸的是,这会引发错误
No index signature with a parameter of type 'string' was found on type '{ ITEM_ARMS_LIGHT: any; ...
我试过像这样输入我的variant
const variant: 'HEAVY' | 'LIGHT' = 'HEAVY';
但是运气不好,出现了同样的错误。有没有办法在不使用禁用注释和保持类型安全的情况下解决这个问题?即 variant
将始终具有解析为 CHARACTER_ITEMS
最佳答案
如果您这样做,我认为不可能使用字符串连接/插值。有一个类似的例子解释了 here它说:
...make sure to use simple string literal assignment with const. This limitation is coming from the type-system, because all the dynamic string operations (e.g. string concatenation, template strings and also object used as a map) will widen the literal type to its super-type,
string
所以我认为您最好的选择可能是拥有一个将您的变体转换为表示 CHARACTER_ITEMS
属性的特定字符串文字的函数。这是一种可能的解决方案:
const convert = (member: "ARMS" | "LEGS", weight: "LIGHT" | "HEAVY") : keyof typeof CHARACTER_ITEMS => {
if (member === "ARMS")
return weight === "LIGHT" ? "ITEM_ARMS_LIGHT" : "ITEM_ARMS_HEAVY"
else
return weight === "LIGHT" ? "ITEM_LEGS_LIGHT" : "ITEM_LEGS_HEAVY"
}
const variant = 'HEAVY'; // This is dynamic, based on server response
//const arms = CHARACTER_ITEMS[`ITEM_LEGS_${variant}`]
const arms = CHARACTER_ITEMS[convert("ARMS", variant)]
关于typescript - 动态访问对象值时修复类型错误,即 myObject [`VALUE_${variable}`],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57395252/