You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将TypeScript联合对象类型转换为接口类型?

将TypeScript联合对象类型转换为接口类型

可以通过映射类型结合条件类型实现需求,以下是具体实现方式:

基础实现(缺失data字段时类型为undefined)

type ActionTypes = { action: 'A', data: number }
| { action: 'B', data: string }
| { action: 'C' }

// 定义类型转换工具
type UnionToInterface<T extends { action: string }> = {
  [K in T['action']]: Extract<T, { action: K }> extends { data: infer D } ? D : undefined;
};

// 转换结果:{ A: number; B: string; C: undefined; }
type Result = UnionToInterface<ActionTypes>

变体实现(缺失data字段时类型为never)

如果希望无data字段的键对应类型为never,只需调整条件类型的分支:

type UnionToInterfaceWithNever<T extends { action: string }> = {
  [K in T['action']]: Extract<T, { action: K }> extends { data: infer D } ? D : never;
};

// 转换结果:{ A: number; B: string; C: never; }
type ResultWithNever = UnionToInterfaceWithNever<ActionTypes>

关键逻辑说明

  • T['action']:提取联合类型中所有action字段的取值,作为目标接口的键名
  • Extract<T, { action: K }>:从联合类型中筛选出action等于当前键K的成员
  • 条件类型判断:检查筛选出的成员是否包含data字段,若包含则通过infer推断出data的类型,否则返回指定默认类型(undefined或never)

内容的提问来源于stack exchange,提问作者lyswhut

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 18:06:39