TypeScript:从字符串数组定义联合类型 [英] TypeScript: Define a union type from an array of strings

查看:46
本文介绍了TypeScript:从字符串数组定义联合类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是第一个遇到这个问题的人,但我的搜索还没有找到任何有用的线索.非常感谢一些 TypeScript 专家的建议.

I can't be the first person coming across this, but my searches have not turned up any useful leads yet. Would greatly appreciate some expert TypeScript advice.

假设我有一个数组:

const fruits = ["Apple", "Orange", "Pear"];

我想定义一个对象,将每个水果映射到一些关于它的有趣事实:

and I want to define an object mapping each fruit to some fun facts about it:

interface Facts {
    color: string,
    typicalWeight: number
}

const fruitFacts: { [key: members of fruits]: Facts } = {
    "Apple": { color: "green", typicalWeight: 150 }
    //
}

我该怎么做 [key: members offruits] 部分?

奖励:我如何强制我的 fruitFacts 对象也用尽从数组派生的所有键,以便在上面的示例中指定 Apples、Oranges 和 Pears 的事实.

Bonus: How do I enforce that my fruitFacts object exhaust all the keys derived from the array as well, so that it specifies facts for Apples, Oranges, and Pears in the example above.

推荐答案

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

TypeScript 3.4 added const assertions which allow for writing this as:

const fruits = ["Apple", "Orange", "Pear"] as const;
type Fruits = typeof fruits[number]; // "Apple" | "Orange" | "Pear"

With as const TypeScript 将上述 fruits 的类型推断为 readonly["Apple", "Orange", "Pear"].以前,它会将其推断为 string[],从而防止 typeoffruit[number] 生成所需的联合类型.

With as const TypeScript infers the type of fruits above as readonly["Apple", "Orange", "Pear"]. Previously, it would infer it as string[], preventing typeof fruits[number] from producing the desired union type.

这篇关于TypeScript:从字符串数组定义联合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆