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: 15 comments 22 replies

Comment options

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

@LMinato
Comment options

@maxpaleo
Comment options

Answer selected by JacobWeisenburger
Comment options

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

@notramo
Comment options

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
3 replies
@candidodmv
Comment options

@AleksandrHovhannisyan
Comment options

@candidodmv
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
3 replies
@Ced-Sharp
Comment options

@maxpaleo
Comment options

@Ced-Sharp
Comment options

Comment options

You must be logged in to vote
1 reply
@candidodmv
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
2 replies
@RonB
Comment options

@AleksandrHovhannisyan
Comment options

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.