Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support ZodDiscriminatedUnion #4854

Open
HaNdTriX opened this issue Sep 3, 2024 · 0 comments
Open

Support ZodDiscriminatedUnion #4854

HaNdTriX opened this issue Sep 3, 2024 · 0 comments

Comments

@HaNdTriX
Copy link

HaNdTriX commented Sep 3, 2024

Is your feature request related to a problem? Please describe.

When creating dependent forms it would be nice to express the form dependencies via Zod.

Describe the solution you'd like

z.discriminatedUnion allows us to do this in a nice matter.

const validationSchema = toTypedSchema(
  z.object({
    type: z
      .enum(["my-optional-number", "my-string", "my-enum", "nothing"])
      .default("my-enum"),
    foo: z.discriminatedUnion("type", [
      z.object({
        type: z.literal("my-optional-number"),
        data: z.number().default(42).optional(),
      }),
      z.object({
        type: z.literal("my-string"),
        data: z.string().default("some string"),
      }),
      z.object({
        type: z.literal("my-enum"),
        data: z.enum(["red", "green", "blue"]).default("red"),
      }),
      z.object({
        type: z.literal("nothing"),
        data: z.never(),
      }),
    ]),
  })
);

Based on the type the schema validation in the schema above adjusts.

type === 'my-optional-number' => foo validates to number
type === 'my-string' => foo validates to string
type === 'my-enum' => foo validates to enum
type === 'nothing' => foo validates to never

Describe alternatives you've considered

https://www.shadcn-vue.com/docs/components/auto-form.html uses a second dsl (dependencies) to solve the issue in a different way. But this approach creates the need to describe the dependencies via second api.

This makes the schema itself useless for the other tasks.

Here is an example using react-hook-forms that implements such a logic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant