From 55f5a1f6decc0993b1a1d1a6a62460fe6d7fdfe2 Mon Sep 17 00:00:00 2001 From: Nathan Hagen Date: Fri, 2 Apr 2021 15:34:43 -0400 Subject: [PATCH] feat(partial): add support for returning type from partial if passed a type --- docs/reference/utilities.md | 2 +- src/structs/utilities.ts | 4 ++-- src/utils.ts | 2 +- test/validation/partial/composed-type.ts | 18 ++++++++++++++++++ 4 files changed, 22 insertions(+), 4 deletions(-) create mode 100644 test/validation/partial/composed-type.ts diff --git a/docs/reference/utilities.md b/docs/reference/utilities.md index 6ff77eff..37dc26ec 100644 --- a/docs/reference/utilities.md +++ b/docs/reference/utilities.md @@ -92,7 +92,7 @@ partial( { name: 'Jane' } ``` -`partial` allows you to create a new struct based on an existing object struct, but with all of its properties being optional. +`partial` allows you to create a new struct based on an existing object or type struct, but with all of its properties being optional. ### `pick` diff --git a/src/structs/utilities.ts b/src/structs/utilities.ts index 1d444c05..c2112561 100644 --- a/src/structs/utilities.ts +++ b/src/structs/utilities.ts @@ -170,7 +170,7 @@ export function omit( } /** - * Create a new struct based on an existing object struct, but with all of its + * Create a new struct based on an existing object or type struct, but with all of its * properties allowed to be `undefined`. * * Like TypeScript's `Partial` utility. @@ -186,7 +186,7 @@ export function partial( schema[key] = optional(schema[key]) } - return object(schema) as any + return (struct.type === 'type' ? type : object)(schema) as any } /** diff --git a/src/utils.ts b/src/utils.ts index ff587244..b0815aca 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -277,7 +277,7 @@ export type Optionalize = OmitBy & Partial> /** - * Transform an object schema type to represent a partial. + * Transform an object or type schema type to represent a partial. */ export type PartialObjectSchema = { diff --git a/test/validation/partial/composed-type.ts b/test/validation/partial/composed-type.ts new file mode 100644 index 00000000..55466867 --- /dev/null +++ b/test/validation/partial/composed-type.ts @@ -0,0 +1,18 @@ +import { partial, type, string, number } from '../../..' + +export const Struct = partial( + type({ + name: string(), + age: number(), + }) +) + +export const data = { + name: 'john', + location: 'mars', +} + +export const output = { + name: 'john', + location: 'mars', +}