【发布时间】:2020-06-18 17:18:38
【问题描述】:
我有一个使用 enum 值作为键的对象。我想迭代那些 enum 值并使用它们来索引所述对象:
enum Foods {
bread = "bread",
meat = "meat",
}
type ShoppingList = {
[Foods.bread]: string;
[Foods.meat]: string;
};
const shoppingList: ShoppingList = {
bread: "1 loaf",
meat: "2 lbs",
};
Object.keys(Foods).forEach((item) => {
console.log(shoppingList[item]);
});
此确实使用 tsc 构建,但 ts-node 和 VS Code 都在报告:
error TS7053: Element implicitly has an 'any' type because expression of type
'string' can't be used to index type 'ShoppingList'. No index signature with
a parameter of type 'string' was found on type 'ShoppingList'.
17 console.log(shoppingList[item]);
~~~~~~~~~~~~~~~~~~
可以理解,因为Object.keys 返回string[]。但是,您和我都知道,这些字符串仅是Foods 的成员。因为ShoppingList只有使用Foods作为它的键,我们应该能够使用Object.keys的任何成员来索引shoppingList。
这在概念上是有道理的,但我如何将它传达给 TypeScript?
编辑:Foods 和 ShoppingList 需要坚持这两个值,即这里没有动态键。
【问题讨论】:
标签: javascript typescript enums