Approach for handling discriminatedUnion
with superRefine
#3830
Unanswered
crisfcodes
asked this question in
Q&A
Replies: 1 comment
-
I use the following function when I have to put schemas with refines (ZodEffects) in a discriminated union. function zDiscriminatedUnion<T extends readonly [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]>(
key: string,
types: T,
): z.ZodUnion<T>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function zDiscriminatedUnion(key: string, types: z.ZodTypeAny[]): any {
const optionsMap = new Map()
for (const type of types) {
const value = (type instanceof z.ZodEffects ? type.sourceType() : type).shape[key]
if (!(value instanceof z.ZodLiteral) || optionsMap.has(value.value)) {
throw new Error('cannot contruct discriminated union')
}
optionsMap.set(value.value, type)
}
return new z.ZodDiscriminatedUnion({
typeName: z.ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
discriminator: key,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options: types as any,
optionsMap,
})
} I hope it helps. Luckily this issue will be solved in zod version 4: #2474 (comment) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Dynamic Validation Schema
Base Schema: Create a base schema that contains common fields.
Dynamic Validations:
code
field.superRefine
in the base schema to maintain shared validation logic across all schemas.Code example
Problem
superRefine
it cannot be applied to the base schema if you plan to use schema methods like merge afterward. This limitation arises becausesuperRefine
returns aZod effect
, which prevents further modifications to the schema.so, how to apply common complex validations(
refine
orsuperRefine
) in the base schema but also running dynamic validations depending schema fields or external data?Aditional notes
I reviewed this question but I didn't see anything to use with this specific case
Beta Was this translation helpful? Give feedback.
All reactions