What You'll Learn
You'll learn how to handle recursive data structures with lazy evaluation in Zod, ensuring TypeScript correctly infers deeply nested types without hitting type-system limitations.
The Problem with Recursive Schemas
Some data structures refer to themselves: a file system where folders contain folders, a comment thread with nested replies, or an organizational chart. When you try to define these schemas in Zod, you hit a wall—TypeScript's type inference can't handle infinite recursion directly.
If you try the naive approach, you'll get a "Type instantiation is excessively deep" error.
Lazy Evaluation with z.lazy()
Zod solves this with lazy evaluation: instead of defining the schema inline, you wrap it in a function that returns the schema. TypeScript delays evaluating the recursive reference until it's actually needed.
import { z } from 'zod';
// A comment can have replies, which are also comments
const CommentSchema: z.ZodType<Comment> = z.lazy(() =>
z.object({
id: z.string(),
text: z.string(),
replies: z.array(CommentSchema)
})
);
type Comment = z.infer<typeof CommentSchema>;
The z.lazy(() => ...) wrapper breaks the circular dependency. The schema function only runs when Zod actually validates data, not when TypeScript analyzes types.
Explicit Type Annotation Required
Notice const CommentSchema: z.ZodType<Comment> — you must explicitly annotate the schema's type. Without it, TypeScript can't infer the recursive structure and will error. This creates a mutual dependency: the schema produces the type, and the type annotation guides the schema.
Real-World Pattern: Nested Categories
const CategorySchema: z.ZodType<Category> = z.lazy(() =>
z.object({
name: z.string(),
subcategories: z.array(CategorySchema).optional()
})
);
type Category = z.infer<typeof CategorySchema>;
// Now TypeScript knows this validates correctly:
const data: Category = {
name: 'Electronics',
subcategories: [
{ name: 'Phones' },
{
name: 'Computers',
subcategories: [{ name: 'Laptops' }]
}
]
};
TypeScript correctly infers the type at every nesting level, and Zod validates the entire tree structure.
Key Takeaway: Use z.lazy() with explicit z.ZodType<T> annotations to define recursive schemas—TypeScript will correctly infer the nested type structure while avoiding infinite recursion errors.