How make all properties of a z.object "non-optional/nullable" #1474
-
Say we have a schema with mixed optional/nullish properties: export const _AvailabilityModel = z.object({
id: z.number().int(),
userId: z.number().int().nullish(),
eventTypeId: z.number().int().nullish(),
days: z.number().int().array(),
startTime: z.date(),
endTime: z.date().optional(),
date: z.date().nullish(),
scheduleId: z.number().int().nullish(),
}) What would be the best way to remove all export const _AvailabilityModel = z.object({
id: z.number().int(),
userId: z.number().int(),
eventTypeId: z.number().int(),
days: z.number().int().array(),
startTime: z.date(),
endTime: z.date(),
date: z.date(),
scheduleId: z.number().int(),
}) |
Beta Was this translation helpful? Give feedback.
Answered by
JacobWeisenburger
Dec 13, 2022
Replies: 1 comment
-
Let me know if this works for you. export const _AvailabilityModel = z.object( {
id: z.number().int(),
userId: z.number().int().nullish(),
eventTypeId: z.number().int().nullish(),
days: z.number().int().array(),
startTime: z.date(),
endTime: z.date().optional(),
date: z.date().nullish(),
scheduleId: z.number().int().nullish(),
} )
type _AvailabilityModel = z.infer<typeof _AvailabilityModel>
// type _AvailabilityModel = {
// userId?: number | null | undefined
// eventTypeId?: number | null | undefined
// endTime?: Date | undefined
// date?: Date | null | undefined
// scheduleId?: number | null | undefined
// id: number
// days: number[]
// startTime: Date
// }
const _AvailabilityModelRequired = z.object(
Object.fromEntries(
Object.entries( _AvailabilityModel.shape )
.map( ( [ key, value ] ) => {
if ( 'innerType' in value._def ) {
if ( 'innerType' in value._def.innerType._def ) {
return [ key, value._def.innerType._def.innerType ]
}
return [ key, value._def.innerType ]
}
return [ key, value ]
} )
)
)
type _AvailabilityModelRequired = {
[ key in keyof _AvailabilityModel ]-?: Exclude<_AvailabilityModel[ key ], null>
}
// type _AvailabilityModelRequired = {
// userId: number
// eventTypeId: number
// endTime: Date
// date: Date
// scheduleId: number
// id: number
// days: number[]
// startTime: Date
// } |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
JacobWeisenburger
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Let me know if this works for you.