TypeScript中Command->Response泛型的返回类型推导实现
TypeScript Command-Response 泛型自动推导实现方案
核心问题说明
你原有写法的问题在于:泛型约束的是所有命令组成的联合类型,TypeScript 处理联合类型的成员属性时只会合并所有项的公共属性,因此返回的_res类型会被推导为所有可能响应的联合类型,无法和入参的具体命令关联。
实现方案
只需要将泛型绑定到命令type字段的字面量类型,通过Key精准匹配对应的命令定义,即可实现入参和返回值的类型关联。
修改后的完整代码如下:
type MappedData<E, T extends keyof E> = E[T]; type MappedType<E> = { [K in keyof E]: { type: K; data: MappedData<E, K>; }; }[keyof E]; interface ServerCommandInterface<T> { _res?: T; } interface TestCommandA extends ServerCommandInterface<{responseA: boolean}> { param_a: string; } interface TestCommandB extends ServerCommandInterface<{responseB: boolean}> { param_b: string; } interface Commands { command_a: TestCommandA; command_b: TestCommandB; } // 核心修改:泛型绑定到命令的type字段的字面量类型 function execute<K extends keyof Commands>(command: { type: K, data: Commands[K] }): Commands[K]['_res'] { // 实际业务逻辑(HTTP调用等) return null as any; } const result = execute({ type: 'command_a', data: { param_a: 'param', } }); // 此时result.responseA会被正确识别为boolean类型 console.log(result.responseA);
方案说明
- 泛型参数
K会根据入参的type字段自动收窄到具体的命令Key,比如传入type: 'command_a'时K会被推导为字面量类型'command_a' - 入参的
data字段会自动匹配Commands[K]对应的类型约束,传入错误字段会直接触发类型报错 - 返回值直接提取
Commands[K]['_res'],即可和入参命令的响应类型一一对应
如果需要保留你原先定义的MappedType类型,也可以把入参替换为Extract<MappedType<Commands>, { type: K }>,效果完全一致。
内容的提问来源于stack exchange,提问作者Marcin Sleziak
相关产品推荐
相关产品推荐

