假设我有一个界面,例如:
interface DataShapes {
shape1: { a: number };
shape2: { b: string };
}
是否可以定义一个类型
ToUnion
使得 ToUnion<DataShapes>
产生一个可区分的联合,例如:
| { key: 'shape1', value: { a: number } }
| { key: 'shape2', value: { b: string } }
是的,这是可能的,这是一种方法: 游乐场
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>
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;
// };
// }