Skip to content

Commit c29848f

Browse files
committed
feat: infer morphism dataSource type from Schema generics
1 parent aea248a commit c29848f

File tree

2 files changed

+27
-9
lines changed

2 files changed

+27
-9
lines changed

src/morphism.ts

+12-9
Original file line numberDiff line numberDiff line change
@@ -291,32 +291,35 @@ export interface Mapper<TSchema extends Schema | StrictSchema, TResult = ResultI
291291
* @param {} type
292292
*
293293
*/
294-
export function morphism<TSchema extends Schema, Source extends object>(
294+
export function morphism<TSchema extends Schema, Source extends SourceFromSchema<TSchema>>(
295295
schema: TSchema,
296296
data: Source
297-
): Source extends (infer _C)[] ? ResultItem<TSchema>[] : ResultItem<TSchema>;
297+
): Source extends any[] ? ResultItem<TSchema>[] : ResultItem<TSchema>;
298298

299-
// morphism({}) => mapper(S) => T
300-
export function morphism<TSchema extends Schema>(schema: TSchema): Mapper<TSchema>;
299+
export function morphism<TSchema extends Schema, Source extends SourceFromSchema<TSchema>>(
300+
schema: TSchema,
301+
data: Source[]
302+
): ResultItem<TSchema>[];
303+
304+
export function morphism<TSchema extends Schema>(schema: TSchema): Mapper<TSchema>; // morphism({}) => mapper(S) => T
301305

302-
// morphism({}, null, T) => mapper(S) => T
303306
export function morphism<TSchema extends Schema, TDestination>(
304307
schema: TSchema,
305308
items: null,
306309
type: Constructable<TDestination>
307-
): Mapper<TSchema, TDestination>;
310+
): Mapper<TSchema, TDestination>; // morphism({}, null, T) => mapper(S) => T
308311

309-
// morphism({}, {}, T) => T
310312
export function morphism<TSchema extends Schema, Target>(
311313
schema: TSchema,
312314
items: SourceFromSchema<TSchema>,
313315
type: Constructable<Target>
314-
): Target;
316+
): Target; // morphism({}, {}, T) => T
317+
315318
export function morphism<Target, Source, TSchema extends Schema<Target, Source>>(
316319
schema: TSchema,
317320
items?: SourceFromSchema<TSchema>,
318321
type?: Constructable<Target>
319-
) {
322+
): any {
320323
if (items === undefined && type === undefined) {
321324
return transformItems(schema);
322325
} else if (schema && items && type) {

src/typescript.spec.ts

+15
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,21 @@ describe('Morphism', () => {
5353
morphism(schema, { s1: 'teest' }).d1.toString();
5454
morphism(schema, [{ s1: 'teest' }]).shift().d1;
5555
morphism(schema, [{ s1: 'teest' }]);
56+
morphism(schema, [{ s1: 'test' }]);
57+
// morphism(schema,[{}])
5658
});
59+
60+
// xit('should fail with typescript', () => {
61+
// interface S {
62+
// s1: string;
63+
// }
64+
// interface D {
65+
// d1: string;
66+
// }
67+
// const schema: StrictSchema<D, S> = {
68+
// d1: 's1'
69+
// };
70+
// morphism(schema, [{ toto: 'test' }]);
71+
// });
5772
});
5873
});

0 commit comments

Comments
 (0)