Skip to content

Commit c3aefad

Browse files
committed
fix: Destination type is properly inferred from source and provided class
1 parent 4280854 commit c3aefad

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/morphism.ts

+11-1
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,17 @@ function morphism<TSchema extends Schema, TDestination>(
148148
type: Constructable<TDestination>
149149
): Mapper<TSchema, TDestination>; // morphism({}, null, T) => mapper(S) => T
150150

151-
function morphism<TSchema extends Schema, Target>(schema: TSchema, items: SourceFromSchema<TSchema>, type: Constructable<Target>): Target; // morphism({}, {}, T) => T
151+
function morphism<
152+
TSchema = Schema<DestinationFromSchema<Schema>, SourceFromSchema<Schema>>,
153+
Target = never,
154+
Source extends SourceFromSchema<TSchema> = SourceFromSchema<TSchema>
155+
>(schema: TSchema, items: Source, type: Constructable<Target>): Target; // morphism({}, {}, T) => T
156+
157+
function morphism<
158+
TSchema = Schema<DestinationFromSchema<Schema>, SourceFromSchema<Schema>>,
159+
Target = never,
160+
Source extends SourceFromSchema<TSchema> = SourceFromSchema<TSchema>
161+
>(schema: TSchema, items: Source[], type: Constructable<Target>): Target[]; // morphism({}, [], T) => T[]
152162

153163
function morphism<Target, Source, TSchema extends Schema<Target, Source>>(
154164
schema: TSchema,

src/typescript.spec.ts

+23
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,29 @@ describe('Typescript', () => {
161161
morphism<StrictSchema<D1, S1>>({ a: ({ _a }) => _a.toString() });
162162
morphism<StrictSchema<D1, S1>>({ a: ({ _a }) => _a.toString() });
163163
});
164+
165+
it('shoud infer result type from source when a class is provided', () => {
166+
class Source {
167+
constructor(public id: number, public ugly_field: string) {}
168+
}
169+
170+
class Destination {
171+
constructor(public id: number, public field: string) {}
172+
}
173+
174+
const source = [new Source(1, 'abc'), new Source(1, 'def')];
175+
176+
const schema: StrictSchema<Destination, Source> = {
177+
id: 'id',
178+
field: 'ugly_field'
179+
};
180+
const expected = [new Destination(1, 'abc'), new Destination(1, 'def')];
181+
182+
const result = morphism(schema, source, Destination);
183+
result.forEach((item, idx) => {
184+
expect(item).toEqual(expected[idx]);
185+
});
186+
});
164187
});
165188

166189
describe('Morphism Function Type Checking', () => {

0 commit comments

Comments
 (0)