我可能不是第一个遇到这个问题的人,但是我的搜索还没有找到任何有用的线索。非常感谢一些专家 TypeScript 建议。
假设我有一个数组:
const fruits = ["Apple", "Orange", "Pear"];
我想定义一个对象,将每种水果映射到一些有趣的事实:
interface Facts {
color: string,
typicalWeight: number
}
const fruitFacts: { [key: members of fruits]: Facts } = {
"Apple": { color: "green", typicalWeight: 150 }
//
}
我该如何处理 [key: members of fruits]
部分?
额外奖励问题:我该如何确保我的 fruitFacts
对象用完了上面例子中数组导出的所有键,以便为苹果、橙子和梨子指定事实。
type FruitName = "Apple" | "Orange"; const fruitNames : FruitName[] = ["Apple", "Orange"];
这段代码吗? - Arash Motamedi