Skip to content

How to change all optional fields to nullish given a zod object? #2050

Discussion options

You must be logged in to vote

Is this what you are looking for?

function makeOptionalPropsNullable<Schema extends z.AnyZodObject> ( schema: Schema ) {
    const entries = Object.entries( schema.shape ) as
        [ keyof Schema[ 'shape' ], z.ZodTypeAny ][]
    const newProps = entries.reduce( ( acc, [ key, value ] ) => {
        acc[ key ] = value instanceof z.ZodOptional
            ? value.unwrap().nullable()
            : value
        return acc
    }, {} as {
        [ key in keyof Schema[ 'shape' ] ]: Schema[ 'shape' ][ key ] extends z.ZodOptional<infer T>
        ? z.ZodNullable<T>
        : Schema[ 'shape' ][ key ]
    } )
    return z.object( newProps )
}

const Person = z.object( {
    firstName: z.string(),

Replies: 4 comments 4 replies

Comment options

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

Comment options

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

@NathanC
Comment options

@convers39
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
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
6 participants