skip to content

Schema-Derived Types

z.infer turns a schema into its TypeScript type, and z.input and z.output differ once a transform or default runs. Interviewers ask which one a signature needs and how .brand stops ids being mixed.

on this pageshow

explore

questions

5

In Zod 4, how do you get a TypeScript type from a schema with z.infer, and why does the call need typeof?

level: juniorimportance: must knowfreq 78%

answer

  1. schema is a value, not a type
  2. typeof lifts value to type
  3. infer aliases the output side
  4. optional field becomes optional key

basics

~20 s

Declare the schema as a value, then write type User = z.infer<typeof User>. The typeof is needed because the schema is a runtime object, and z.infer reads the parsed-output type that Zod attaches to it.

solid answer

~40 s

A Zod schema such as `z.object({ ... })` is a JavaScript value whose class also carries the static type of what `.parse()` returns. `z.infer<typeof User>` extracts it: `typeof` turns the value into its type, and `z.infer` reads the data type out of the schema type. An `.optional()` field comes out as an optional key, `nickname?: string | undefined`. By convention the schema and the type share one name, which works because TypeScript keeps values and types in separate namespaces. `z.infer` is an alias of `z.output`, so it describes the parsed result; once a transform or default runs, `z.input` gives the accepted side instead. The value returned by `.parse()` already has the inferred type, so it rarely needs an annotation.

code

typescript · 17 lines
typescript
import * as z from "zod";

const Player = z.object({
  username: z.string(),
  email: z.email(),
  nickname: z.string().optional(),
});

type Player = z.infer<typeof Player>;
// { username: string; email: string; nickname?: string | undefined }

function greet(player: Player): string {
  return `Hello, ${player.nickname ?? player.username}`;
}

const player = Player.parse({ username: "ada", email: "[email protected]" });
greet(player);

go deeper

for a junior

Recall the exact spelling, z.infer<typeof Schema>, and be able to say why typeof is there: the schema is a value, and generics take types.

for a middle

Explain what the inferred type looks like for optional, nullable and enum fields, and that z.infer is the output side, so a transform changes it.

for a senior

Show you know when z.infer is the wrong helper, namely raw data before parsing when transforms or defaults run, and reach for z.input there.

for a principal

Talk about keeping one exported schema and its derived type per module, so no hand-written interface drifts from the runtime check.

## What `z.infer` does A Zod schema such as `z.object({ ... })` is an ordinary **JavaScript value**: an object you can call `.parse()` and `.safeParse()` on. Its class also carries, at the type level, the shape of the data that `.parse()` returns. `z.infer` is the helper that reads that shape out and gives it to you as a plain TypeScript type. ```ts import * as z from "zod"; const Player = z.object({ username: z.string(), email: z.email(), nickname: z.string().optional(), }); type Player = z.infer<typeof Player>; // { username: string; email: string; nickname?: string | undefined } ``` Nothing runs at runtime here. `z.infer` exists only for the compiler; it neither validates nor converts anything. ## Why the call needs `typeof` `z.infer` is a generic **type**, and a generic type takes a type argument. `Player` on the right-hand side is a value, not a type, so `z.infer<Player>` does not compile. The TypeScript operator `typeof`, used in a type position, turns a value into its static type, here something like `ZodObject<{ username: ZodString; ... }>`. `z.infer` then extracts the parsed-data type from that schema type. - `typeof Player` is the **schema's** type: the Zod object class with its field schemas. - `z.infer<typeof Player>` is the **data's** type: `{ username: string; ... }`. - Writing `type Player = typeof Player` is a common slip: it names the schema class, so a function typed with it expects a schema, not a player. ## What the inferred type looks like Zod maps each schema to a TypeScript type in a predictable way: | Schema | Inferred type | |---|---| | `z.string()` | `string` | | `z.email()` | `string` | | `z.string().optional()` inside an object | optional key: `nickname?: string \| undefined` | | `z.string().nullable()` | `string \| null` | | `z.enum(["admin", "member"])` | `"admin" \| "member"` | | `z.array(z.number())` | `number[]` | Two details matter in interviews. First, an **optional field becomes an optional key** (the `?`), not a required key whose type merely includes `undefined`. Second, format schemas such as `z.email()` still infer `string`: the format is checked at runtime, and the static type does not change. ## `z.infer` is the output type In Zod 4's source, `infer` is exported as an alias of `output`. That means `z.infer<typeof S>` describes what `S.parse()` **returns**, which is not always what it accepts. Once a schema contains a `.transform()` or a `.default()`, the two sides can differ: `z.string().transform((s) => s.length)` accepts a string, but `z.infer` of it is `number`. The companion helper `z.input<typeof S>` gives the accepted side. For most plain schemas the two are identical, which is why `z.infer` is the everyday choice. The return value of `.parse()` already carries this type, so you rarely annotate a parsed variable by hand: ```ts const player = Player.parse(JSON.parse(body)); // player: { username: string; email: string; nickname?: string | undefined } ``` ## How the type is carried `z.infer` can do this because every schema class is generic over two type parameters. In Zod 4 the base class is `ZodType<Output, Input>`, and each concrete class fills them in: `z.string()` carries `string` for both, an object schema carries the object type built from its fields. `.parse()` is declared to return the output parameter, which is why its result is typed without help. - `z.infer<typeof S>` and `z.output<typeof S>` read the output parameter. - `z.input<typeof S>` reads the input parameter. - The schema class still exposes an `_output` property, but Zod 4 marks it deprecated in favour of `z.output<typeof schema>`; the helpers are the supported route. Because the type lives on the schema value, editing the schema (adding a field, making one optional) changes every use of the derived type at the next compile, with nothing else to update. ## Conventions that keep this clean 1. Declare the schema once, with `const`, and derive the type right below it. 2. Give the schema and the type the **same name** (`Player` and `Player`). TypeScript keeps values and types in separate namespaces, so the two never clash, and an import of `Player` brings both. 3. Export the type with the schema, so other modules never re-declare the shape by hand. 4. Reach for `z.input` instead of `z.infer` when a function handles data **before** it is parsed. ## Common slips - Writing `z.infer<Player>` without `typeof`: a compile error, because `Player` is a value. - Expecting `z.infer` to check data: it is erased at compile time, and only `.parse()` or `.safeParse()` validates. - Typing a raw, unparsed payload with `z.infer` when the schema transforms or defaults a field: the type claims the converted shape before any conversion has happened. - Hand-writing an `interface` beside the schema and letting the two drift: deriving the type removes the second copy.

  • Why can the schema constant and the inferred type both be called Player without a clash?
    TypeScript keeps values and types in separate namespaces. `const Player` lives in the value namespace and `type Player` in the type namespace, so each use site picks the right one from context. One `import { Player }` brings both, which is why the same-name convention is popular in Zod codebases.
  • When is z.infer the wrong helper for a function parameter?
    When the function receives data before it is parsed and the schema changes the type on the way through, for example a `.transform()` from string to Date or a `.default()` that fills a missing key. `z.infer` is the output side, so it would demand the converted shape. Use `z.input<typeof Schema>` for raw data and keep `z.infer` for code after the parse.
  • Does a value returned by Player.parse() need a type annotation?
    No. `.parse()` is typed to return the schema's output type, the same type `z.infer` gives, so the variable is inferred correctly. An explicit annotation only adds a second place to keep in sync.

  • z.infer<Player> works without typeof because Player is the schema.
  • z.infer checks the data at runtime, like a lightweight parse.
  • z.infer gives the type you pass into parse, not the one it returns.
  • An optional field infers as a required key whose type includes undefined.
  • type Player = typeof Player gives the shape of a player object.
open as a page

In Zod 4, how do you type a category tree schema whose subcategories nest the same schema, and what fixes a circularity error?

level: middleimportance: should knowfreq 32%

basics

~20 s

Put 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.

open as a page

In Zod 4, what does .brand<"UserId">() change about a schema's inferred type and parse result, and how does that keep UserId and OrderId apart?

level: seniorimportance: should knowfreq 38%

basics

~20 s

It intersects the schema's output type with z.$brand<"UserId">, so short of a cast, only values returned by that schema's parse fit a UserId parameter, and an OrderId does not. The runtime value stays a plain string, and by default the input type is unbranded.

open as a page

In Zod 4, a user schema turns createdAt from an ISO string into a Date and defaults role when absent; what do z.input and z.output give, and which does each signature need?

level: seniorimportance: should knowfreq 52%

basics

~20 s

z.input is what parse accepts: createdAt a string, role an optional key. z.output, which z.infer aliases, is what parse returns: createdAt a Date, role required. Raw data before parsing takes the input type; code after parsing takes the output type.

open as a page

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?

level: seniorimportance: nice to knowfreq 28%

basics

~10 s

Constrain 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().

open as a page