Created
September 20, 2022 12:51
-
-
Save capaj/34f29b87ac8c96e199aa623e54231db2 to your computer and use it in GitHub Desktop.
generates default object for a given zod schema, you can supply an object to override the defaults
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { z } from 'zod' | |
/** | |
* generates default object for a given zod schema, you can supply an object to override the defaults | |
*/ | |
export const zodSchemaDefaults = <Schema extends z.ZodFirstPartySchemaTypes>( | |
schema: Schema, | |
override?: Partial<z.TypeOf<Schema>> | |
): z.TypeOf<Schema> => { | |
if (override !== undefined && typeof override !== 'object') { | |
return override | |
} | |
switch (schema._def.typeName) { | |
case z.ZodFirstPartyTypeKind.ZodDefault: | |
return schema._def.defaultValue() | |
case z.ZodFirstPartyTypeKind.ZodObject: { | |
// The switch wasn't able to infer this but the cast should | |
// be safe. | |
return Object.fromEntries( | |
Object.entries((schema as z.SomeZodObject).shape).map( | |
([key, value]) => [key, zodSchemaDefaults(value, override?.[key])] | |
) | |
) | |
} | |
case z.ZodFirstPartyTypeKind.ZodString: | |
return '' | |
case z.ZodFirstPartyTypeKind.ZodNull: | |
return null | |
case z.ZodFirstPartyTypeKind.ZodNullable: | |
return null | |
case z.ZodFirstPartyTypeKind.ZodNumber: | |
return 0 | |
case z.ZodFirstPartyTypeKind.ZodBoolean: | |
return false | |
// etc | |
default: | |
return null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment