gpt4 book ai didi

TypeScript:从字符串数组定义联合类型

转载 作者:搜寻专家 更新时间:2023-10-30 20:32:32 27 4
gpt4 key购买 nike

我不是第一个遇到这个问题的人,但我的搜索还没有找到任何有用的线索。非常感谢一些专业的 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 对象也耗尽从数组派生的所有键,以便它在上面的示例中指定苹果、橘子和梨的事实。

最佳答案

添加了 TypeScript 3.4 const assertions允许将其写为:

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] 生成所需的联合类型。

关于TypeScript:从字符串数组定义联合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52085454/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com