Skip to content

Retrieve default values from schema #1953

Discussion options

You must be logged in to vote

Is this what you are looking for?

function getDefaults<Schema extends z.AnyZodObject>(schema: Schema) {
    return Object.fromEntries(
        Object.entries(schema.shape).map(([key, value]) => {
            if (value instanceof z.ZodDefault) return [key, value._def.defaultValue()]
            return [key, undefined]
        })
    )
}

const schema = z.object({
    name: z.string().default('todo'),
    demo: z.number(),
})

console.log(getDefaults(schema))
// { name: 'todo', demo: undefined }

Replies: 12 comments 11 replies

Comment options

You must be logged in to vote
2 replies
@ArekBartnik
Comment options

@LMinato
Comment options

Answer selected by JacobWeisenburger
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
3 replies
@naviens
Comment options

@JacobWeisenburger
Comment options

@lukasvice
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
5 replies
@lucas-santosP
Comment options

@TonyGravagno
Comment options

@TonyGravagno
Comment options

@lucas-santosP
Comment options

@wjbright
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@Ced-Sharp
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
Converted from issue

This discussion was converted from issue #1944 on January 29, 2023 17:34.