Z
Zod7mo ago
shadi

shadi - hey everyone, i've been struggling with...

hey everyone, i've been struggling with building a recursive zod schema. I tried following the docs: https://github.com/colinhacks/zod?tab=readme-ov-file#recursive-types but still can't figure it out for my use case. here is what I'm trying to achieve:
const BranchSchema = z.object({
prompt: BranchPromptSchema, // regular object schema
branches: z.array(ConfigSchema),
});

const ConfigSchema = z.union([
z.object({
name: z.string(),
branch: BranchSchema,
actions: z.undefined(),
}),
z.object({
name: z.string(),
branch: z.undefined(),
actions: z.array(ActionSchema),
}),
]);
const BranchSchema = z.object({
prompt: BranchPromptSchema, // regular object schema
branches: z.array(ConfigSchema),
});

const ConfigSchema = z.union([
z.object({
name: z.string(),
branch: BranchSchema,
actions: z.undefined(),
}),
z.object({
name: z.string(),
branch: z.undefined(),
actions: z.array(ActionSchema),
}),
]);
thanks in advance 🙏
Solution:
You have to manually type either direction of the types, for example: ```ts const ActionSchema = z.object({ ... }); const BranchPromptSchema = z.object({ ... });...
Jump to solution
2 Replies
Solution
Sikari
Sikari7mo ago
You have to manually type either direction of the types, for example:
const ActionSchema = z.object({ ... });

const BranchPromptSchema = z.object({ ... });

const BranchSchema = z.object({
prompt: BranchPromptSchema,
branches: z.lazy(() => z.array(ConfigSchema)),
});

type Config = {
name: string;
branch: z.infer<typeof BranchSchema>;
actions: undefined;
} | {
name: string;
branch: undefined;
actions: z.infer<typeof ActionSchema>[];
};

const ConfigSchema: z.ZodType<Config> = z.union([
z.object({
name: z.string(),
branch: BranchSchema,
actions: z.undefined(),
}),
z.object({
name: z.string(),
branch: z.undefined(),
actions: z.array(ActionSchema),
}),
]);
const ActionSchema = z.object({ ... });

const BranchPromptSchema = z.object({ ... });

const BranchSchema = z.object({
prompt: BranchPromptSchema,
branches: z.lazy(() => z.array(ConfigSchema)),
});

type Config = {
name: string;
branch: z.infer<typeof BranchSchema>;
actions: undefined;
} | {
name: string;
branch: undefined;
actions: z.infer<typeof ActionSchema>[];
};

const ConfigSchema: z.ZodType<Config> = z.union([
z.object({
name: z.string(),
branch: BranchSchema,
actions: z.undefined(),
}),
z.object({
name: z.string(),
branch: z.undefined(),
actions: z.array(ActionSchema),
}),
]);
shadi
shadiOP7mo ago
thanks alot, that worked perfectly!
Want results from more Discord servers?
Add your server