In Zod 4, how do you type a category tree schema whose subcategories nest the same schema, and what fixes a circularity error?
answer
- a const cannot read itself
- defer the reference
- a getter on the shape
- annotate the getter's return type
basics
~20 sPut the self-reference in a getter on the shape: get subcategories() { return z.array(Category) }. z.infer then yields a recursive type with no hand-written interface. If TypeScript reports an implicit-any circularity error, annotate that getter's return type.
solid answer
~40 sA direct `subcategories: z.array(Category)` fails because `Category` is read before it exists. In Zod 4 you write the field as a getter, `get subcategories() { return z.array(Category); }`: the getter defers the read at runtime, and TypeScript's handling of getter-based recursive objects lets `z.infer` produce `{ name: string; subcategories: Category[] }` without a cast. The schema stays a normal `ZodObject`, so `.extend()` and `.pick()` still work, and mutual recursion uses getters on both sides. Inference is finicky in more complex shapes; when TypeScript reports that the getter implicitly returns `any` (TS7023), give it an explicit return type such as `z.ZodNullable<z.ZodArray<typeof Activity>>`. `z.lazy` with a hand-written type remains for non-object recursion such as a JSON value.
code
typescript · 25 linesimport * as z from "zod";
const Category = z.object({
name: z.string(),
get subcategories() {
return z.array(Category);
},
});
type Category = z.infer<typeof Category>;
// { name: string; subcategories: Category[] }
const tree: Category = {
name: "Books",
subcategories: [{ name: "Fiction", subcategories: [] }],
};
Category.parse(tree);
// When inference gives up (TS7023), annotate the getter:
const Activity = z.object({
name: z.string(),
get subactivities(): z.ZodNullable<z.ZodArray<typeof Activity>> {
return z.nullable(z.array(Activity));
},
});go deeper
Recall the getter form, get subcategories() { return z.array(Category) }, and that z.infer then gives the recursive type.
Explain why the getter works: it defers the runtime read, and TypeScript handles getter-based recursive objects, so no interface or cast is needed.
Diagnose the implicit-any circularity error, fix it with a getter return annotation, and know when z.lazy fits better.
Judge when deep recursive schemas cost more in compile-time friction than they save, and where a hand-written type at the boundary is the steadier choice.
## The problem: a schema that contains itself A category tree is the classic self-referential shape: each category has a name and a list of subcategories, and each subcategory is a category. The obvious attempt fails: ```ts const Category = z.object({ name: z.string(), subcategories: z.array(Category), // Category is used before it is initialised }); ``` `z.object()` runs immediately, while `Category` is still being declared, so JavaScript has no value to read yet, and TypeScript rejects the use before declaration. Even if the value existed, TypeScript would have to infer a type that refers to itself, and plain inference refuses to do that: it reports the constant as implicitly `any` instead. A recursive schema therefore needs two things at once, a **deferred runtime read** and a **type the compiler can resolve**. ## The Zod 4 getter pattern Zod 4 solves both halves with a **getter** on the object shape: ```ts import * as z from "zod"; const Category = z.object({ name: z.string(), get subcategories() { return z.array(Category); }, }); type Category = z.infer<typeof Category>; // { name: string; subcategories: Category[] } ``` - At **runtime**, the getter delays reading `Category` until Zod needs the field's schema, by which time the constant exists. - At the **type level**, TypeScript can resolve a recursive object type declared through a getter, which is what Zod relies on, so `z.infer` yields a properly recursive type with **no hand-written interface and no cast**. - The result is a plain `ZodObject`, so `.pick()`, `.omit()`, `.partial()` and `.extend()` all work as usual. Optional nesting reads naturally with a method chain: `get subcategories() { return z.array(Category).optional(); }`. ## Mutual recursion The same trick covers two schemas that refer to each other, such as a user with posts and a post with an author: each side puts its reference in a getter (`get posts() { return z.array(Post); }`, `get author() { return User; }`). Neither needs to be declared first. ## Circularity errors and the fix The Zod docs warn that recursive inference is **finicky** and works only in certain scenarios. Some more complicated shapes make TypeScript give up with an error like *"'subactivities' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions"* (TS7023). The documented way out: 1. Find the getter TypeScript names in the error. 2. Give it an **explicit return type** spelled with Zod's schema classes, for example `get subactivities(): z.ZodNullable<z.ZodArray<typeof Activity>> { ... }`. 3. Keep the rest of the schema inferred; in the docs' example, that one annotation is enough. Which shapes trip the error depends on the exact nesting and on the TypeScript version, so treat the getter annotation as the **standing fallback** rather than trying to predict failures. Annotating only the getter keeps the rest of the schema inferred, so the derived type still follows later edits. ## Zod 3 contrast, and where `z.lazy` still fits | Approach | Type comes from | Cast or annotation | Result | |---|---|---|---| | Getter on the shape (Zod 4) | `z.infer` | none in the usual case | a full `ZodObject` | | `z.lazy(() => ...)` with a hand-written type | a separate `interface` | `z.ZodType<Node>` annotation required | a lazy wrapper | Zod's own Zod 4 announcement contrasts the getter with the **Zod 3 pattern for recursive types, which required type casting**. `z.lazy` still exists in Zod 4 and is right for recursion that is not an object, such as a JSON value that is a union of primitives, arrays and records; Zod's own `z.json()` is built that way. Without an explicit annotation, TypeScript reports the lazy constant as implicitly `any`. ## Edges worth knowing - Cyclic **input data** (an object that contains itself) parses with Zod's classic API, and the output graph mirrors the input graph; Zod Mini needs a memoizer registered through `z.config` first. - Mutually recursive schemas and the object methods (`.pick()`, `.partial()`, `.extend()`) combine freely, since each result is still a `ZodObject`. - `z.input` and `z.output` follow the recursion too, so a transform inside the recursive schema splits both sides at every depth.
- How do you write two schemas that refer to each other, such as a User with posts and a Post with an author?Put each cross-reference in a getter: `get posts() { return z.array(Post); }` on `User` and `get author() { return User; }` on `Post`. The getters defer both reads until Zod needs them, so either schema can be declared first, and `z.infer` produces the two mutually recursive types.
- When is z.lazy still the right tool in Zod 4?When the recursion is not an object referring to objects, for example a JSON value that is a union of strings, numbers, arrays and records. A getter lives on an object key, so a value that is itself a union at the top has no key to hang it on. With `z.lazy` you declare the type yourself and annotate the constant, such as `const Json: z.ZodType<JsonValue> = z.lazy(...)`.
- A const schema can reference itself directly inside z.object().
- Zod 4 recursive object schemas still need a hand-written interface and a cast.
- A getter-based schema loses object methods such as .extend() and .pick().
- A circularity error means Zod cannot validate the tree at runtime.
- Turning off noImplicitAny is the right fix for a recursive getter error.
Assumes Zod 4, whose getter-based recursive objects infer without a cast; the Zod 3 pattern for recursive types required a hand-written type and casting.