Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zod recursive type with discriminated union

Tags:

zod

typescript

How to transform this recursive discriminated union to zod?

interface TextInput {
  type: 'text-input'
}

interface Group {
  type: 'group';
  components: AppComponent[]
}

type AppComponent = TextInput | Group

const component: AppComponent = {
  type: 'group',
  components: [{
    type: 'text-input'
  }],
}

what would the zod version look like?

My attempt:

import { z } from 'zod';

const TextInputSchema = z.object({
    type: z.literal('text-input'),
});

const GroupSchema = z.object({
    type: z.literal('group'),
    components: z.array(ComponentSchema),
});

const ComponentSchema = z.discriminatedUnion('type', [TextInputSchema, GroupSchema]);

but that doesn't work due to the error that [...] type is referenced directly or indirectly in its own initializer.

like image 701
feerlay Avatar asked Oct 27 '25 15:10

feerlay


2 Answers

the key here is to use z.lazy which let's us use zod types that haven't yet been completely defined.

import {z} from "zod"

interface TextInput {
  type: 'text-input'
}

interface Group {
  type: 'group';
  components: AppComponent[]
}

type AppComponent = TextInput | Group

const TextInput = z.object({
  type: z.literal("text-input")
})

const Group: z.ZodType<Group> = z.lazy(() => z.object({
  type: z.literal("group"),
  components: AppComponent.array()
}))

const AppComponent = TextInput.or(Group)

const component = AppComponent.parse({
  type: 'group',
  components: [
    { type: 'text-input' }, 
    { 
      type: "group",
      components: [
        { type: 'text-input' }
      ]
    }
  ],
})

console.log(component)
like image 84
mizerlou Avatar answered Oct 29 '25 07:10

mizerlou


The earlier answer uses a union type rather than a discriminated union as requested in the question. It is possible to use recursive discriminated union types in Zod, but the example they give in Zod documentation must be slightly modified.

Here is an example:

const TextInputSchema = z.object({
  type: z.literal('text-input'),
});

const BaseGroupSchema = z.object({
  type: z.literal("group"),
});

type Group = z.infer<typeof BaseGroupSchema> & {
  components: Component[];
}

const GroupSchema: z.ZodDiscriminatedUnionOption<"type"> = BaseGroupSchema.extend({
  components: z.lazy(() => z.array(ComponentSchema))
})

const ComponentSchema = z.discriminatedUnion('type', [
  TextInputSchema,
  GroupSchema
]);

type Component = z.infer<typeof ComponentSchema>;

Notice that type of GroupSchema is z.ZodDiscriminatedUnionOption<"type"> rather than z.ZodType<Group> as one may think from the documentation examples.


The code above can be tested with this example:


const testInput = {
  type: 'group', components: [
    { type: 'text-input' },
    { type: 'group', components: [
        { type: 'text-input' }
     ]}
]}

console.log(ComponentSchema.parse(testInput)) ;
// {
//      type: 'group',
//      components: [ { type: 'text-input' }, { type: 'group', components: [Array] } ]
// }
like image 26
Mifeet Avatar answered Oct 29 '25 07:10

Mifeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!