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

2023-12-31

我不是第一个遇到此问题的人,但我的搜索尚未找到任何有用的线索。非常感谢 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] part?

奖励:我如何强制执行我的fruitFacts对象还耗尽从数组派生的所有键,以便它指定上例中的苹果、橙子和梨的事实。


添加了 TypeScript 3.4const断言 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions允许将其写为:

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

With as constTypeScript 推断类型fruits以上为readonly["Apple", "Orange", "Pear"]。以前,它会将其推断为string[], 预防typeof fruits[number]从产生所需的联合类型。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TypeScript:从字符串数组定义联合类型 的相关文章

随机推荐