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

如何将Typescript带$case标记的联合类型转换为普通对象类型

TypeScript 联合类型转换实现

可以实现,直接通过TS的**键重映射(Key Remapping)**特性就能完成该泛型工具的开发,具体实现如下:

// 原类型定义
export type UnionType = {
    element:
        | { $case: 'a'; a: number }
        | { $case: 'b'; b: string }
        | { $case: 'c'; c: boolean };
};

// 泛型工具实现
type OneOfConverter<T extends { element: { $case: string } }> = {
  // 遍历element的所有联合分支,用$case的值作为新键,提取对应属性的类型作为值
  [Branch in T['element'] as Branch['$case']]: Branch[Branch['$case']]
};

// 测试转换
type ObjectType = OneOfConverter<UnionType>;
// 转换后结果符合预期:
// type ObjectType = {
//     a: number;
//     b: string;
//     c: boolean;
// }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:45:05