typescript 如何使一个以联合类型为键的记录对所有值都不是强制性的?

gijlo24d  于 2023-06-24  发布在  TypeScript
关注(0)|答案(1)|浏览(129)

在typescript项目中,我在类型中有一个封闭的字符串属性:

type SubscriptionLevel = 'normal' | 'premium' | 'cancelled';

我想创建一个类似于map的对象,它使用这个类型作为键,但不是所有值都必须这样。
一个非常简单的例子是:

const badgeIcon : Record<SubscriptionLevel, string | undefined> = {
    'premium' : 'crown',
    'cancelled' : 'grayed',
}

我只想为某些值指定Map值(这里我得到的是字符串,但实际代码会导致渲染react组件不同)。
此代码在运行时运行,但Typescript抱怨Property 'normal' is missing in type '{ premium: string; cancelled: string; }' but required in type 'Record<SubscriptionLevel, string | undefined>'.(2741)
我可以通过添加normal键来修复代码:

const badgeIcon : Record<SubscriptionLevel, string | undefined> = {
    'premium' : 'crown',
    'cancelled' : 'grayed',
    'normal': undefined
}

但是这种方法需要穷举,即使只有少数kay应该有a值(我的实际代码有10个键,但只有2个必须设置)。
所以我的问题是有没有简单的方法来创建这个Map,并使用可选值?
类型安全很重要,所以我不想使用'string'作为键,因为它不会检查拼写错误。

laik7k3q

laik7k3q1#

您正在寻找内置实用程序类型Partial:

type SubscriptionLevel = 'normal' | 'premium' | 'cancelled';

const badgeIcon: Partial<Record<SubscriptionLevel, string | undefined>> = {
  premium: 'crown',
  cancelled: 'grayed',
};

相关问题