Replies: 2 comments 2 replies
-
Lemme make sure I understand what you're asking here: you want a static way to extract a (potentially recursive) object that represents any "default" values in a given It's probably doable since the default value is stored in the Line 3183 in 72fa277 |
Beta Was this translation helpful? Give feedback.
1 reply
-
Ok I got it semi-hacky but seems to do the job: import { AnyZodObject, ZodDefault, ZodTypeAny } from 'zod'
import { TypeOf } from 'zod/lib/types'
const objectHandler = (zodRef: AnyZodObject): Record<string, ZodTypeAny> =>
Object.keys(zodRef.shape).reduce((carry, key) => {
const res = generateDefaults<ZodTypeAny>(zodRef.shape[key])
return {
...carry,
...(res ? { [key]: res } : {})
}
}, {} as Record<string, ZodTypeAny>)
export const generateDefaults = <T extends ZodTypeAny>(zodRef: T): TypeOf<typeof zodRef> => {
const typeName = zodRef._def.typeName
if (/ZodObject|ZodRecord/.test(typeName)) {
return objectHandler(zodRef as any)
} else if (/ZodDefault/.test(typeName)) {
return (zodRef as any as ZodDefault<T>)._def.defaultValue()
}
return undefined
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Is there a way to extract an object from a schema that recursively collects all default values without using deepPartial or the need to provide a dummy object for non-optional properties?
I use zod with react-hook-form and looking for a way to set default values inside the schema.
Great work, btw.
Beta Was this translation helpful? Give feedback.
All reactions