Skip to content

Commit

Permalink
fix: object type merge
Browse files Browse the repository at this point in the history
  • Loading branch information
izatop committed Nov 10, 2020
1 parent fb759b3 commit f690a04
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
18 changes: 17 additions & 1 deletion packages/input/src/Type/ObjectType.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {entriesReverse, isFunction, isInstanceOf, isObject, MayNullable} from "@typesafeunit/util";
import {AssertionObjectError, AssertionTypeError, IReadableTypeError} from "../Assertion";
import {ObjectFields} from "../interfaces";
import {ObjectFields, ObjectTypeMerge} from "../interfaces";
import {TypeAbstract} from "../TypeAbstract";

export class ObjectType<TValue extends Record<string, any>> extends TypeAbstract<TValue, Record<string, any>> {
Expand All @@ -17,6 +17,22 @@ export class ObjectType<TValue extends Record<string, any>> extends TypeAbstract
return this.#name;
}

public get fields(): ObjectFields<TValue> {
return this.#fields;
}

public merge<F extends Record<string, any>>(from: ObjectTypeMerge<F>): ObjectType<TValue & F> {
if (isInstanceOf(from, ObjectType)) {
return new ObjectType<TValue & F>(
Object.assign({}, this.fields, from) as any,
);
}

return new ObjectType<TValue & F>(
Object.assign({}, this.fields, from.fields) as any,
);
}

public async validate(payload: MayNullable<Record<string, any>>): Promise<TValue> {
this.assert(isObject(payload), `Wrong payload: ${this.name} expected`, payload);

Expand Down
2 changes: 2 additions & 0 deletions packages/input/src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,5 @@ export type FieldSelectType<T> = T extends Record<string, any>
: T extends Array<infer I>
? List<I>
: TypeAbstract<T>;

export type ObjectTypeMerge<T extends Record<string, any>> = ObjectType<T> | ObjectFields<T>;

0 comments on commit f690a04

Please sign in to comment.