Skip to content

Render conditional fields with zod discriminatedUnion #451

Answered by edmundhung
hauptrolle asked this question in Q&A
Discussion options

You must be logged in to vote

I am sure it supports discriminatedUnion at the top level (at some point). But it might be either a regression on v1 types or something wrong with nested types that I will need to check.

For now, you can cast it to FieldMetadata manually like this:

const schema = z.object({
  deliveryPaused: z.boolean().optional(),
  name: z.string({ required_error: "validations.required" }),
  type: z.discriminatedUnion("$case", [
    z.object({
      $case: z.literal("pollWeb"),
      pollWeb: pollWebSchema,
    }),
    z.object({
      $case: z.literal("pushWeb"),
      pushWeb: pushWebSchema,
    }),
  ]),
});

const pollWebSchema = z.object({
  token: z.string({ required_error: "validations.required" })

Replies: 1 comment 5 replies

Comment options

You must be logged in to vote
5 replies
@hauptrolle
Comment options

@edmundhung
Comment options

Answer selected by hauptrolle
@hauptrolle
Comment options

@edmundhung
Comment options

@hauptrolle
Comment options

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