zod icon indicating copy to clipboard operation
zod copied to clipboard

Recursive type with discriminated union

Open tomaszferens opened this issue 2 years ago • 0 comments

Hey 👋

How to transform this recursive discriminated union to zod?

interface TextInput {
  type: 'text-input';
}

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

type AppComponent = TextInput | Group;

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.

tomaszferens avatar Dec 06 '22 17:12 tomaszferens