In Zod 4, how should a generic helper that accepts any schema type its parameter so callers keep the parsed type and the schema's own methods?
answer
- infer the schema, not the data
- constrain a type parameter
- z.output of the parameter
- Input now defaults to unknown
basics
~10 sConstrain a type parameter, function f<T extends z.ZodType>(schema: T), and type the result as z.output<T>. Writing schema: z.ZodType<Out> collapses the argument to the base type, losing the subclass and methods such as .min().
solid answer
~40 sDeclare `function f<T extends z.ZodType>(schema: T, data: unknown): z.output<T>`. `T` is inferred from the argument, so the helper keeps the exact class, such as `ZodString` with `.min()`, and `z.output<T>` gives callers the parsed type; on success, `schema.safeParse(data).data` is already typed that way. Putting the data type in the generic instead, `schema: z.ZodType<Out>`, erases the subclass, which Zod's library-author guide calls incorrect. In Zod 4 the base class is `ZodType<Output = unknown, Input = unknown>`, so `z.ZodTypeAny` is no longer needed and `z.ZodType<Date>` accepts a schema that transforms a string into a `Date`. Narrow `T` to what the helper needs, such as `z.ZodObject` or `z.ZodType<string>`; a library that must also accept Zod Mini schemas constrains on the core `$ZodType` and calls the top-level `z.parse`.
code
typescript · 21 linesimport * as z from "zod";
function parseOrNull<T extends z.ZodType>(schema: T, data: unknown): z.output<T> | null {
const result = schema.safeParse(data);
return result.success ? result.data : null;
}
function keepSchema<T extends z.ZodType>(schema: T): T {
return schema;
}
const name = parseOrNull(z.string().min(1), "Ada"); // string | null
const email = keepSchema(z.email()).max(254); // still a ZodEmail with its methods
function onlyStrings<T extends z.ZodType<string>>(schema: T): T {
return schema;
}
onlyStrings(z.email()); // ok
// onlyStrings(z.number()); // compile error: output is number, not string
console.log(name, email.parse("[email protected]"));go deeper
Recall the shape f<T extends z.ZodType>(schema: T) and that z.output<T> turns the schema type into the parsed-data type.
Explain why inferring the schema keeps its subclass and methods, while z.ZodType<Out> collapses it to the base type.
Know the Zod 4 generics, Output and Input defaulting to unknown with ZodTypeAny gone, and use them to narrow what a helper accepts.
Decide whether shared helpers target the classic API or the core types, trading method convenience against supporting Zod Mini callers.
## The pattern A helper that works with "any Zod schema" (parse-or-null, a typed fetch wrapper, a config loader) should take the schema as a **constrained type parameter** and describe its result with `z.output`: ```ts import * as z from "zod"; function parseOrNull<T extends z.ZodType>(schema: T, data: unknown): z.output<T> | null { const result = schema.safeParse(data); return result.success ? result.data : null; } const name = parseOrNull(z.string().min(1), "Ada"); // string | null ``` Three pieces do the work: - **`T extends z.ZodType`** keeps the exact schema class the caller passed (`ZodString`, `ZodObject<...>`), because `T` is inferred from the argument. - **`z.output<T>`** (the same as `z.infer<T>`) turns that schema type into the parsed-data type, so callers get `string`, not `unknown`. - `schema.safeParse()` on a `T` returns a result whose `data` is already typed as `z.output<T>`. ## Why not `schema: z.ZodType<Out>` The tempting signature puts the data type in the generic instead: | Signature | What a caller gets back for `z.string()` | |---|---| | `function f<T extends z.ZodType>(schema: T): T` | `ZodString`, with `.min()`, `.email()` and the rest | | `function f<Out>(schema: z.ZodType<Out>)` returning the schema | `ZodType<string>`, the base type with string-specific methods gone | Zod's guide for library authors calls this form **incorrect** (it shows it with the core `$ZodType<T>`, the base the classic `z.ZodType` extends): it limits TypeScript's ability to infer the argument, and it loses which subclass was passed. If all you return is parsed data, `z.ZodType<Out>` can work, but the constrained parameter costs nothing and keeps every option open. ## What Zod 4 changed in the generics The base class changed shape between major versions: 1. **Zod 3**: `ZodType<Output, Def, Input = Output>`. Three parameters, and `Input` defaulted to `Output`. 2. **Zod 4**: `ZodType<Output = unknown, Input = unknown>`. The `Def` parameter is gone, and `Input` now defaults to `unknown`. 3. **`z.ZodTypeAny` is no longer needed**: `z.ZodType` on its own accepts any schema. The `Input = unknown` default matters in practice. In Zod 4, `const s: z.ZodType<Date> = z.iso.datetime().transform((v) => new Date(v))` compiles, because only the output is constrained. Under Zod 3's default, the input type would have been pinned to `Date`, and a string-to-Date schema would not fit. ## Helpers that take a value of the schema's type `z.output<T>` is just as useful for **parameters** as for return types. A helper that attaches a fallback value can require that the fallback matches what the schema produces: ```ts function withDefault<T extends z.ZodType>(schema: T, value: z.output<T>) { return schema.nullish().transform((val) => val ?? value); } const displayName = withDefault(z.string(), "anonymous"); // ok // withDefault(z.string(), 42); // compile error: 42 is not a string ``` TypeScript infers `T` from the first argument and then checks the second against that schema's output type, so a mismatched fallback fails at compile time instead of producing a value of the wrong type at runtime. ## Narrowing what the helper accepts Constrain `T` to say exactly what the helper needs: - **Any schema**: `T extends z.ZodType`. - **Object schemas only**, so the helper may call `.extend()` or read `.shape`: `T extends z.ZodObject`. - **Schemas whose output is a string**: `T extends z.ZodType<string>`; passing `z.number()` is a compile error. - **Both sides**: `T extends z.ZodType<Date, string>` accepts a schema that turns a string into a `Date` and rejects `z.date()`, whose input is a `Date`. ## Helpers in a library that supports Zod Mini Code that must accept schemas from both the classic API and Zod Mini constrains against the **core** interface instead: `import * as z4 from "zod/v4/core"` and `T extends z4.$ZodType`. The core classes have **no methods**, so the helper calls the top-level functions, for example `z.parse(schema, data)` with `z4.output<T>` as the return type, rather than `schema.parse(data)`. ## Traps - Returning `z.input<T>` from a parsing helper: parse returns the output side, so transforms and defaults would be typed wrongly. - Writing `z.ZodTypeAny` in new code: it is unnecessary in Zod 4. - Annotating the parameter as the bare base type `z.ZodType`, with no type parameter: the helper compiles, but every result is `unknown`. - Calling `.parse()` on a `z4.$ZodType` in library code: the method does not exist on the core type.
- Why does z.ZodType<Date> accept a schema that turns an ISO string into a Date in Zod 4?Because Zod 4's `ZodType<Output = unknown, Input = unknown>` leaves the input unconstrained when you give only the output. The transform's input is `string` and its output `Date`, so it fits. In Zod 3, `Input` defaulted to `Output`, which pinned the input to `Date` too. To constrain both sides in Zod 4, write `z.ZodType<Date, string>`.
- How does a library that must accept both classic Zod and Zod Mini schemas write the same helper?It imports the core types, `import * as z4 from "zod/v4/core"`, constrains `T extends z4.$ZodType` and returns `z4.output<T>`. The core classes carry no methods, so it parses with the top-level `z.parse(schema, data)` or `z.safeParse` rather than calling a method on the schema.
- schema: z.ZodType<T> is the best signature because it infers T directly.
- In Zod 4 you need z.ZodTypeAny to accept an arbitrary schema.
- z.ZodType<Date> rejects a schema that transforms a string into a Date.
- A parsing helper should return z.input<T> because it receives input.
- Library code can call schema.parse() on a core $ZodType.
Assumes Zod 4, where ZodType is ZodType<Output = unknown, Input = unknown> and z.ZodTypeAny is unnecessary; in Zod 3 it was ZodType<Output, Def, Input = Output>.