作者:nnyoyo8 | 来源:互联网 | 2022-12-06 11:53
我不能成为遇到这个问题的第一个人,但我的搜索还没有发现任何有用的线索.非常感谢一些专家的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
对象耗尽从数组派生的所有键,以便它在上面的例子中指定苹果,橘子和梨的事实.
1> Ben Regenspa..:
TypeScript 3.4添加了const
断言,可以将其编写为:
const fruits = ["Apple", "Orange", "Pear"] as const;
type Fruits = typeof fruits[number]; // "Apple" | "Orange" | "Pear"
使用as const
TypeScript可以将fruits
上述类型推断为readonly["Apple", "Orange", "Pear"]
。以前,它将推断为string[]
,从而typeof fruits[number]
无法生成所需的联合类型。
2> Titian Cerni..:
它可以完成,但首先你需要一个额外的函数来帮助推断数组元素的字符串文字类型.默认情况下string[]
,即使数组是常量,也会推断出数组.在我们有一个字符串文字类型数组之后,我们可以使用类型查询来获得所需的类型
function stringLiteralArray(a: T[]) {
return a;
}
const fruits = stringLiteralArray(["Apple", "Orange", "Pear"]);
type Fruits = typeof fruits[number]