Skip to content

Commit

Permalink
feat: allows custom types to be passed to avoid cast to ObjectSchema (#…
Browse files Browse the repository at this point in the history
…1358)

* Allows custom types to be passed to avoid cast to Object Schema - i.e. File, Data, js-joda Time, etc.

* Fixed bug with lazy object instantiation
  • Loading branch information
cipacda authored May 7, 2021
1 parent 70d0b67 commit 94cfd11
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 8 deletions.
16 changes: 8 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,25 +37,25 @@ function addMethod(schemaType: any, name: string, fn: any) {
schemaType.prototype[name] = fn;
}

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

type SchemaOf<T> = T extends Array<infer E>
? ArraySchema<SchemaOf<E> | Lazy<SchemaOf<E>>>
: T extends Date
type SchemaOf<T, CustomTypes = never> = T extends Array<infer E>
? ArraySchema<SchemaOf<E, CustomTypes> | Lazy<SchemaOf<E, CustomTypes>>>
: T extends Date | CustomTypes
? BaseSchema<Maybe<T>, AnyObject, T>
: T extends AnyObject
? ObjectSchemaOf<T>
? ObjectSchemaOf<T, CustomTypes>
: BaseSchema<Maybe<T>, AnyObject, T>;

export type AnyObjectSchema = ObjectSchema<any, any, any, any>;
Expand Down
30 changes: 30 additions & 0 deletions test/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,36 @@ SchemaOfDateArray: {
});
}

SchemaOfFile: {
type Document = {
file: File;
date_uploaded: Date;
notes: string;
};

type FileSchema = SchemaOf<Document, File>;

const _t: FileSchema = object({
file: mixed<File>().defined(),
date_uploaded: date().defined(),
notes: string().defined(),
});
}

SchemaOfFileArray: {
type DocumentWithFullHistory = {
history: File[];
name: string;
};

type DocumentWithFullHistorySchema = SchemaOf<DocumentWithFullHistory, File>;

const _t: DocumentWithFullHistorySchema = object({
name: string().defined(),
history: array().of(mixed<File>().defined())
});
}


{
// const str = string();
Expand Down

0 comments on commit 94cfd11

Please sign in to comment.