Skip to content

Commit

Permalink
fix(types): SchemaOf doesn't produce a union of base schema
Browse files Browse the repository at this point in the history
  • Loading branch information
jquense committed Dec 10, 2020
1 parent b53e5f2 commit 2d71f32
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,25 @@ function addMethod(schemaType: any, name: string, fn: any) {
schemaType.prototype[name] = fn;
}

type ObjectSchemaOf<T extends AnyObject> = ObjectSchema<
{
[k in keyof T]-?: T[k] extends AnyObject
? // we can't use ObjectSchema<{ []: SchemaOf<T[k]> }> b/c TS produces a union of two schema
ObjectSchemaOf<T[k]>
: T[k] extends Array<infer E>
? ArraySchema<SchemaOf<E>>
: BaseSchema<Maybe<T[k]>, AnyObject, T[k]>;
}
>;

type SchemaOf<T> = T extends AnyObject
? ObjectSchema<{ [k in keyof T]: SchemaOf<T[k]> }>
? ObjectSchemaOf<T>
: T extends Array<infer E>
? ArraySchema<SchemaOf<E>>
: BaseSchema<Maybe<T>, AnyObject, T>;

export type AnyObjectSchema = ObjectSchema<any, any, any, any>;

export type { SchemaOf, TypeOf, Asserts, Asserts as InferType, AnySchema };

export {
Expand Down
4 changes: 4 additions & 0 deletions test/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,12 +186,16 @@ ObjectOmit: {
SchemaOf: {
type Person = {
firstName: string;
title: string | undefined;
age?: number;
};

type PersonSchema = SchemaOf<Person>;

const _t: PersonSchema = object({
firstName: string().defined(),
title: string(),
age: number(),
});
}

Expand Down

0 comments on commit 2d71f32

Please sign in to comment.