In Zod 4, how do you get a TypeScript type from a schema with z.infer, and why does the call need typeof?
answer
- schema is a value, not a type
- typeof lifts value to type
- infer aliases the output side
- optional field becomes optional key
basics
~20 sDeclare 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 sA 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 linesimport * 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
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.
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.
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.
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.