如何将TypeScript对象类型直接映射为函数独立参数?
TypeScript事件类型转直接参数函数类型的实现
要实现将事件属性直接作为函数参数(而非包裹在对象中),只需修改EventToFunction类型的逻辑,直接提取事件的属性名和类型作为函数参数即可。
完整代码
// 假设ImageGeneration已定义 type ImageGeneration = { /* 你的类型定义 */ }; type DreamEventSchema = | { type: 'GENERATION_COMPLETE', generation: ImageGeneration } | { type: 'IMAGE_VOTE', voteForId: string } | { type: 'SCORE_SCREEN_DONE' } | { type: 'SUBMIT_THEME', theme: string } | { type: 'THEME_VOTE', voteForId: string } type EventToFunction<Events extends { type: string }> = { [E in Events as E['type']]: Omit<E, 'type'> extends infer Rest ? keyof Rest extends never ? () => void : Rest extends Record<infer K, infer V> ? ( [K]: V ) => void : never : never } type result = EventToFunction<DreamEventSchema>;
解析结果
修改后的result会被TypeScript解析为你期望的形式:
type result = { GENERATION_COMPLETE: (generation: ImageGeneration) => void; IMAGE_VOTE: (voteForId: string) => void; SCORE_SCREEN_DONE: () => void; SUBMIT_THEME: (theme: string) => void; THEME_VOTE: (voteForId: string) => void; }
关键逻辑说明
Omit<E, 'type'>:移除每个事件类型中的type字段,得到该事件的有效属性集合keyof Rest extends never:判断有效属性集合是否为空,为空则生成无参函数Rest extends Record<infer K, infer V>:通过类型推断提取有效属性的名称K和对应的类型V,直接将其作为函数的参数名和类型
内容的提问来源于stack exchange,提问作者Gerald Lang
相关产品推荐
相关产品推荐

