Skip to content

Required object with optional fields #2751

Discussion options

You must be logged in to vote

Is this what you are looking for?

const objectSchema = z.object( {
    first: z.string(),
    second: z.string(),
} )

const schema = z.object( {
    field2: z.union( [
        objectSchema,
        objectSchema.pick( { first: true } ),
        objectSchema.pick( { second: true } ),
    ] )
} )

console.log( schema.safeParse( { field2: { first: 'bar' } } ).success ) // true
console.log( schema.safeParse( { field2: { second: 'bar' } } ).success ) // true
console.log( schema.safeParse( { field2: { first: 'foo', second: 'bar' } } ).success ) // true
console.log( schema.safeParse( { field2: {} } ).success ) // false

If you found my answer satisfactory, please consider supporting me. Even a sm…

Replies: 3 comments 4 replies

Comment options

You must be logged in to vote
1 reply
@florianakos
Comment options

Comment options

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

@JacobWeisenburger
Comment options

Answer selected by JacobWeisenburger
@muhsin-life
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
4 participants
Converted from issue

This discussion was converted from issue #2749 on September 21, 2023 16:54.