|
7 | 7 | // https://github.com/the-draupnir-project/interface-manager |
8 | 8 | // </text> |
9 | 9 |
|
10 | | -import { Presentation, PresentationTypeWithoutWrap } from "./Presentation"; |
| 10 | +import { |
| 11 | + ObjectTypeFromPresentationType, |
| 12 | + Presentation, |
| 13 | + PresentationTypeWithoutWrap, |
| 14 | +} from "./Presentation"; |
11 | 15 |
|
12 | 16 | export enum PresentationSchemaType { |
13 | 17 | Single = "Single", |
@@ -104,15 +108,40 @@ export function printPresentationSchema(schema: PresentationSchema): string { |
104 | 108 | } |
105 | 109 | } |
106 | 110 |
|
107 | | -type UnionOfObjectTypes<T extends PresentationTypeWithoutWrap[]> = { |
108 | | - [P in keyof T]: T[P] extends PresentationTypeWithoutWrap<infer U> ? U : never; |
| 111 | +type Acceptor<ObjectType = unknown> = |
| 112 | + | PresentationSchema<ObjectType> |
| 113 | + | PresentationTypeWithoutWrap<ObjectType>; |
| 114 | +export type ObjectTypeFromAcceptor<T> = T extends PresentationTypeWithoutWrap |
| 115 | + ? ObjectTypeFromPresentationType<T> |
| 116 | + : T extends PresentationSchema |
| 117 | + ? ObjectTypeForPresentationSchema<T> |
| 118 | + : never; |
| 119 | + |
| 120 | +type UnionOfObjectTypes<T extends Acceptor[]> = { |
| 121 | + [P in keyof T]: T[P] extends Acceptor<infer U> ? U : never; |
109 | 122 | }[number]; |
110 | 123 |
|
111 | | -export function union<TPresentationTypes extends PresentationTypeWithoutWrap[]>( |
112 | | - ...presentationTypes: TPresentationTypes |
113 | | -): UnionPresentationSchema<UnionOfObjectTypes<TPresentationTypes>> { |
| 124 | +export function union< |
| 125 | + TAcceptor extends (PresentationTypeWithoutWrap | UnionPresentationSchema)[], |
| 126 | +>( |
| 127 | + ...acceptors: TAcceptor |
| 128 | +): UnionPresentationSchema<UnionOfObjectTypes<TAcceptor>> { |
| 129 | + type PresentationTypeForUnion = PresentationTypeWithoutWrap< |
| 130 | + UnionOfObjectTypes<TAcceptor> |
| 131 | + >; |
| 132 | + const presentationTypes = acceptors.reduce<PresentationTypeForUnion[]>( |
| 133 | + (acc, acceptor) => { |
| 134 | + if ("schemaType" in acceptor) { |
| 135 | + acc.push(...(acceptor.variants as PresentationTypeForUnion[])); |
| 136 | + } else { |
| 137 | + acc.push(acceptor as PresentationTypeForUnion); |
| 138 | + } |
| 139 | + return acc; |
| 140 | + }, |
| 141 | + [] |
| 142 | + ); |
114 | 143 | return { |
115 | 144 | schemaType: PresentationSchemaType.Union, |
116 | 145 | variants: presentationTypes, |
117 | | - } as UnionPresentationSchema<UnionOfObjectTypes<TPresentationTypes>>; |
| 146 | + } as UnionPresentationSchema<UnionOfObjectTypes<TAcceptor>>; |
118 | 147 | } |
0 commit comments