TypeScript中如何限制对象键为指定联合类型成员?
问题:限制对象键为指定联合类型的值
我定义了如下TypeScript代码:
type Currencies = "tl" | "us-dollar" | "euro" const currenciesMap = {}
希望限制currenciesMap对象的键只能是Currencies联合类型中定义的值,示例符合要求的对象如下:
const currenciesMap = { tl: "₺", "us-dollar": "$", euro: "€" }
要求TypeScript仅允许上述键被定义。我尝试了以下写法但未成功:
const currenciesMap: { [key: Currencies[string]]: string } = {}
TypeScript报错信息为:
An index signature parameter type must be 'string', 'number', 'symbol', or a template literal type.
请问如何正确定义该类型?
解决方案
方法一:使用内置Record类型
TypeScript内置的Record工具类型专门用于定义“键为指定类型、值为统一类型”的对象,直接就能满足需求:
type Currencies = "tl" | "us-dollar" | "euro" const currenciesMap: Record<Currencies, string> = { tl: "₺", "us-dollar": "$", euro: "€" }
Record<K, V>会生成一个对象类型,所有键都属于类型K,对应的值都属于类型V,完美匹配你的要求。
方法二:手动定义映射类型
如果不想依赖内置工具类型,也可以手动通过映射类型实现等价效果:
type Currencies = "tl" | "us-dollar" | "euro" type CurrencyMap = { [K in Currencies]: string } const currenciesMap: CurrencyMap = { tl: "₺", "us-dollar": "$", euro: "€" }
[K in Currencies]会遍历联合类型的每个成员,将其作为对象的键,最终生成的类型和Record完全一致。
允许部分键可选
如果不需要一开始就定义所有键,可以用Partial工具类型包裹,让所有键变为可选:
const currenciesMap: Partial<Record<Currencies, string>> = { tl: "₺" } // 此时仅定义tl键也不会报错,后续可补充其他键
内容的提问来源于stack exchange,提问作者user21281053
相关产品推荐
相关产品推荐

