Skip to content

How to discard paricular field in .refine() or somewhere else without changing the schema? #2811

Answered by JacobWeisenburger
xsjcTony asked this question in Q&A
Discussion options

You must be logged in to vote

Is this what you are looking for?

import _ from 'lodash'

const baseUserSchema = z.object( {
    name: z.string().min( 1 ),
    age: z.string().pipe( z.coerce.number().min( 18 ) ),
    id_type: z.enum( [ 'passport', 'driver_license' ] ),
    passport: z.string().optional(),
    driver_license: z.string().optional(),
} )

const requiredFields: ( keyof typeof baseUserSchema.shape )[] = [
    'name',
    'age',
    'id_type',
]

const userSchema = baseUserSchema.transform( x => _.pick( x, [ ...requiredFields, x.id_type ] ) )
type User = z.infer<typeof userSchema>
// type User = {
//     name: string;
//     age: number;
//     id_type: "passport" | "driver_license";
//     passport?: string …

Replies: 1 comment

Comment options

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

This discussion was converted from issue #2525 on September 26, 2023 16:37.