是否可以根据接口的键以编程方式将接口转换为可区分联合?

问题描述 投票:0回答:2

假设我有一个界面,例如:

interface DataShapes {
  shape1: { a: number };
  shape2: { b: string };
}

是否可以定义一个类型

ToUnion
使得
ToUnion<DataShapes>
产生一个可区分的联合,例如:

 | { key: 'shape1', value: { a: number } }
 | { key: 'shape2', value: { b: string } }
typescript
2个回答
0
投票

是的,这是可能的,这是一种方法: 游乐场

interface DataShapes {
  shape1: { a: number };
  shape2: { b: string };
}

type ToUnion<T extends object> = {
    [K in keyof T]: {
        key: K,
        value: T[K]
    }
}[keyof T]

type A = ToUnion<DataShapes>

0
投票
type ToUnion<T> = {
  [K in keyof T]: { key: K; value: T[K] }
}[keyof T];

interface DataShapes {
  shape1: { a: number };
  shape2: { b: string };
}

type Result = ToUnion<DataShapes>;
// {
//     key: "shape1";
//     value: {
//         a: number;
//     };
// } | {
//     key: "shape2";
//     value: {
//         b: string;
//     };
// }

TS游乐场

© www.soinside.com 2019 - 2024. All rights reserved.