Skip to content

Instantly share code, notes, and snippets.

@capaj
Created September 20, 2022 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save capaj/34f29b87ac8c96e199aa623e54231db2 to your computer and use it in GitHub Desktop.
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
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