Help me make a recursive zod v4 schema for my interface #5330
alekseykurylev
started this conversation in
General
Replies: 1 comment
-
|
It looks strange and unreliable, but I haven't found any other solution. onst FieldBaseSchema = z.object({
id: z.string(),
name: z.string(),
label: z.string(),
description: z.string(),
});
const FieldTextSchema = z.object({
...FieldBaseSchema.shape,
type: z.literal("text"),
value: z.string(),
});
const FieldNumberSchema = z.object({
...FieldBaseSchema.shape,
type: z.literal("number"),
value: z.number(),
});
const ItemSchema: z.ZodType<TItem> = z.lazy(() =>
z.discriminatedUnion("type", [
FieldTextSchema,
FieldNumberSchema,
GroupListSchema,
GroupSchema,
FormSchema,
]),
);
const GroupListSchema = z.object({
type: z.literal("group-list"),
items: z.array(z.record(z.string(), ItemSchema)),
});
const DynamicFormBaseSchema = z.object({
id: z.string(),
label: z.string(),
items: z.record(z.string(), ItemSchema),
});
const GroupSchema = z.object({
...DynamicFormBaseSchema.shape,
type: z.literal("group"),
});
const FormSchema = z.object({
...DynamicFormBaseSchema.shape,
type: z.literal("form"),
params: z.record(z.string(), z.unknown()),
});
export const DynamicFormSchema = z.discriminatedUnion("type", [
GroupSchema,
FormSchema,
]);
export type DynamicForm = z.infer<typeof DynamicFormSchema>;
// 🤷🤷🤷
type TItem =
| z.infer<typeof FieldTextSchema>
| z.infer<typeof FieldNumberSchema>
| {
type: "group-list";
items: Record<string, TItem>[];
}
| {
type: "group";
id: string;
label: string;
items: Record<string, TItem>;
}
| {
type: "form";
id: string;
label: string;
items: Record<string, TItem>;
params: Record<string, unknown>;
};
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Help me make a recursive zod v4 schema for my interface
I can't seem to get the desired result. And I don't understand how to do recursive schemes correctly in zod v4.
Beta Was this translation helpful? Give feedback.
All reactions