我不能成为遇到这个问题的第一个人,但我的搜索还没有发现任何有用的线索.非常感谢一些专家的TypeScript建议.
说我有一个数组:
const fruits = ["Apple", "Orange", "Pear"];
Run Code Online (Sandbox Code Playgroud)
我想定义一个对象,将每个水果映射到一些有趣的事实:
interface Facts {
color: string,
typicalWeight: number
}
const fruitFacts: { [key: members of fruits]: Facts } = {
"Apple": { color: "green", typicalWeight: 150 }
//
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做[key: members of fruits]?
额外:我如何强制我的fruitFacts对象耗尽从数组派生的所有键,以便它在上面的例子中指定苹果,橘子和梨的事实.
Ben*_*pan 29
TypeScript 3.4添加了const断言,可以将其编写为:
const fruits = ["Apple", "Orange", "Pear"] as const;
type Fruits = typeof fruits[number]; // "Apple" | "Orange" | "Pear"
Run Code Online (Sandbox Code Playgroud)
使用as constTypeScript可以将fruits上述类型推断为readonly["Apple", "Orange", "Pear"]。以前,它将推断为string[],从而typeof fruits[number]无法生成所需的联合类型。
Tit*_*mir 15
它可以完成,但首先你需要一个额外的函数来帮助推断数组元素的字符串文字类型.默认情况下string[],即使数组是常量,也会推断出数组.在我们有一个字符串文字类型数组之后,我们可以使用类型查询来获得所需的类型
function stringLiteralArray<T extends string>(a: T[]) {
return a;
}
const fruits = stringLiteralArray(["Apple", "Orange", "Pear"]);
type Fruits = typeof fruits[number]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3165 次 |
| 最近记录: |