TypeScript中使用自定义类型作为Record键并初始化为空的问题
解决TypeScript中自定义联合类型作为Record键的初始化问题
问题原因
Record<MyCustomType, number> 类型要求对象必须包含 MyCustomType 联合类型中的所有键,且每个键对应的值必须是 number 类型。空对象 {} 缺少 property1 和 property2 这两个必填属性,因此会触发类型错误。
解决方案:用Partial包裹Record类型
你可以通过 Partial 工具类型将 Record 的所有属性转为可选,这样空对象就能符合类型要求,同时还能保留自定义键的约束(只能使用 MyCustomType 中的键)。
示例代码:
type MyCustomType = 'property1' | 'property2'; class MyClass { public myRecord: Partial<Record<MyCustomType, number>> = {}; }
类型说明
Partial<Record<MyCustomType, number>>等价于{ [K in MyCustomType]?: number },即每个键都是可选的number类型。- 后续给
myRecord添加属性时,TypeScript 会自动检查键是否属于MyCustomType,值是否为number类型,确保类型安全。
等价写法(直接定义可选索引类型)
如果你不想嵌套使用工具类型,也可以直接定义可选的索引签名,效果和上面完全一致:
type MyCustomType = 'property1' | 'property2'; class MyClass { public myRecord: { [key in MyCustomType]?: number } = {}; }
这样既满足了初始化为空对象的需求,又避免了将类型放宽为 Record<string, number>(后者会允许任意字符串键,失去自定义类型的约束意义)。
内容的提问来源于stack exchange,提问作者BalB
相关产品推荐
相关产品推荐

