【发布时间】:2019-02-04 17:10:23
【问题描述】:
我不可能是第一个遇到这个问题的人,但我的搜索还没有找到任何有用的线索。非常感谢一些 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 对象也耗尽从数组派生的所有键,以便在上面的示例中指定 Apples、Oranges 和 Pears 的事实。
【问题讨论】:
-
你知道编译时的确切字符串吗?如果不是,则不能定义这样的类型。
-
假设我愿意。我可以避免复制它们吗?即避免做
type FruitName = "Apple" | "Orange"; const fruitNames : FruitName[] = ["Apple", "Orange"];
标签: typescript