Skip to content

Commit

Permalink
fix: Destination type is properly inferred from source and provided c…
Browse files Browse the repository at this point in the history
…lass
  • Loading branch information
emyann committed Aug 30, 2019
1 parent 4280854 commit c3aefad
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/morphism.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,17 @@ function morphism<TSchema extends Schema, TDestination>(
type: Constructable<TDestination>
): Mapper<TSchema, TDestination>; // morphism({}, null, T) => mapper(S) => T

function morphism<TSchema extends Schema, Target>(schema: TSchema, items: SourceFromSchema<TSchema>, type: Constructable<Target>): Target; // morphism({}, {}, T) => T
function morphism<
TSchema = Schema<DestinationFromSchema<Schema>, SourceFromSchema<Schema>>,
Target = never,
Source extends SourceFromSchema<TSchema> = SourceFromSchema<TSchema>
>(schema: TSchema, items: Source, type: Constructable<Target>): Target; // morphism({}, {}, T) => T

function morphism<
TSchema = Schema<DestinationFromSchema<Schema>, SourceFromSchema<Schema>>,
Target = never,
Source extends SourceFromSchema<TSchema> = SourceFromSchema<TSchema>
>(schema: TSchema, items: Source[], type: Constructable<Target>): Target[]; // morphism({}, [], T) => T[]

function morphism<Target, Source, TSchema extends Schema<Target, Source>>(
schema: TSchema,
Expand Down
23 changes: 23 additions & 0 deletions src/typescript.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,29 @@ describe('Typescript', () => {
morphism<StrictSchema<D1, S1>>({ a: ({ _a }) => _a.toString() });
morphism<StrictSchema<D1, S1>>({ a: ({ _a }) => _a.toString() });
});

it('shoud infer result type from source when a class is provided', () => {
class Source {
constructor(public id: number, public ugly_field: string) {}
}

class Destination {
constructor(public id: number, public field: string) {}
}

const source = [new Source(1, 'abc'), new Source(1, 'def')];

const schema: StrictSchema<Destination, Source> = {
id: 'id',
field: 'ugly_field'
};
const expected = [new Destination(1, 'abc'), new Destination(1, 'def')];

const result = morphism(schema, source, Destination);
result.forEach((item, idx) => {
expect(item).toEqual(expected[idx]);
});
});
});

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

0 comments on commit c3aefad

Please sign in to comment.