Can zod make recursive schema? #2245
-
I want to create nested menu. so I wonder wether Zod schema has it or not. here is my current code : type InfinityText = {
text: string
children: InfinityText[]
}
function NestedMenu(props: { menu: InifinityText }) {}
<NestedMenu menu={[{text:"parent", children: [ { text: "children" } ] } ] } /> I try to do this but got error, because of declaration. const infinityTextSchema = z.object({ text: z.string(), children: z.array(infinityTextSchema) }); Please help me to create those schema. big thanks. 👍 |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
https://github.com/colinhacks/zod#recursive-types If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
-
Hello, relating to this, is there a way to use preprocess with this recursive schema pattern? This works:
But if I change
Any clue why this is happening and how to solve it? |
Beta Was this translation helpful? Give feedback.
-
inferring from recursive schema gives any type. this is issue with z.lazy() method |
Beta Was this translation helpful? Give feedback.
-
Here's a more robust solution that merges both the input and output types if you're doing transforms in your schemas: export type ZodCompositeType<
T extends ZodTypeAny,
U extends { [K in keyof U]: ZodType<any, ZodTypeDef, any> },
> = ZodType<
z.output<T> & { [K in keyof U]: z.output<U[K]> },
ZodTypeDef,
z.input<T> & { [K in keyof U]: z.input<U[K]> }
>; You'd use const customerField = Customer.or(string().transform(Number)); // type transform would cause errors with `z.infer<...> & { ... }` as that only merges the output.
export const PaymentMethod: ZodCompositeType<
typeof basePaymentMethod,
{ customer: typeof customerField }
> = basePaymentMethod.extend({
customer: z.lazy(() => customerField),
}); |
Beta Was this translation helpful? Give feedback.
https://github.com/colinhacks/zod#recursive-types
If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏
https://github.com/sponsors/JacobWeisenburger