Zod discriminated union "other string" option #5391
Replies: 2 comments 1 reply
-
|
Zod's For your use case—where 1. Use a custom transform/refinement: const schema = z.object({
val: z.string(),
a: z.string(),
}).superRefine((data, ctx) => {
if (data.val === "A" && !data.a) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "`a` is required when `val` is 'A'",
path: ["a"],
});
}
});2. Use the upcoming const schema = z.switch((input) => {
if (input.val === "A") {
return z.object({ val: z.literal("A"), a: z.string().min(1) });
}
return z.object({ val: z.string(), a: z.string() });
});3. Community workaround with If your question is answered, please close the issue! If you need a more tailored example, let me know your Zod version and I can help further. To reply, just mention @dosu. How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other |
Beta Was this translation helpful? Give feedback.
-
|
It seems like the best option is to do the following: This works, but it isn't ideal because it uses a |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I'd like to be able to create a Zod schema like the following:
Here,
ais only required whenvalisA. For any other value ofval, it can be empty. Currently, Zod's discriminated union feature doesn't allow non-literal discriminator values and soz.string()cannot be used.I've also tried writing this with a regular
z.union(). However, an input of{ val: "A", a: "" }successfully parses because the second union member is matched (see this playground link).Is there a way to build a schema that can have a
z.string()option as a fallback for the discriminated union?Beta Was this translation helpful? Give feedback.
All reactions