如何创建同时包含固定键与指定可选动态键的Typescript对象类型
问题原因
你写的两种不生效的写法存在以下问题:
- 第一种写法的映射语法
[key: K in APIMethods]不能直接和静态字段声明放在同一个对象类型定义中,映射语法只能单独用于构造完整的映射类型 - 第二种写法的索引签名要求所有
APIMethods枚举的键都必须存在,不满足可选的要求,同时会要求静态字段的类型也匹配索引签名的返回值限制
基础实现方案(支持0~N个动态键可选)
使用类型交叉将固定字段类型和动态可选字段的映射类型合并即可:
export type APIMethods = 'getA' | 'getB' | 'getC'; // 固定必填字段类型 type FixedFields = { divId: string; role: string; }; // 动态可选字段映射类型 type DynamicOptionalFields = { [K in APIMethods]?: any; }; // 交叉合并得到最终类型 export type Item = FixedFields & DynamicOptionalFields;
也可以简化为一行写法:
export type Item = { divId: string; role: string } & { [K in APIMethods]?: any };
该实现下divId和role为必填字段,getA/getB/getC均为可选字段,你给出的三个示例结构都可以正常通过类型校验。
进阶实现方案(恰好只允许存在1个动态键)
如果需要严格匹配你给出的示例逻辑,要求三个动态键必须且只能出现一个,可以使用互斥联合类型实现:
export type APIMethods = 'getA' | 'getB' | 'getC'; type FixedFields = { divId: string; role: string; }; // 构造每个动态键单独存在的联合类型 type DynamicSingleField = { [K in APIMethods]: Record<K, any> & Partial<Record<Exclude<APIMethods, K>, never>> }[APIMethods]; export type Item = FixedFields & DynamicSingleField;
该实现下只允许三个动态键中恰好存在一个,同时出现多个或者一个都没有都会触发类型报错。
内容的提问来源于stack exchange,提问作者Clifford Fajardo
相关产品推荐
相关产品推荐

