How to discard paricular field in .refine()
or somewhere else without changing the schema?
#2811
-
Re-use the example in #2524: In the example above, I first entered something in I know this is expected since I defined it in the schema, just want to know whether there's a way to get around? The discarding totally satisfies the schema, since both I'm aware that I can use And I want the interface to looks like a simple single one instead of complex // This is what I need
interface User {
name: string;
age: number;
id_type: 'passport' | 'driver_license'
driver_license?: string;
passport?: string;
}
// Instead of
type User = {
name: string;
age: number;
} & ({
id_type: 'passport';
passport: string;
} | {
id_type: 'driver_license'
driver_license: string;
})
// Or
type User = {
id_type: 'passport';
name: string;
age: number;
passport: string;
} | {
id_type: 'driver_license';
name: string;
age: number;
driver_license: string;
} In Or, as another solution, is it possible to make a new feature that removes all |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
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 | undefined;
// driver_license?: string | undefined;
// }
console.log(
userSchema.parse( {
age: '50',
driver_license: '456',
id_type: 'driver_license',
name: 'abc',
passport: '123',
} )
)
// {
// name: "abc",
// age: 50,
// id_type: "driver_license",
// driver_license: "456"
// }
console.log(
userSchema.parse( {
age: '50',
driver_license: '456',
id_type: 'passport',
name: 'abc',
passport: '123',
} )
)
// {
// name: "abc",
// age: 50,
// id_type: "passport",
// passport: "123"
// } If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
Is this what you are looking for?