如何将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
相关产品推荐
相关产品推荐

