Synchronize validation and types
Define a TypeScript type from an object schema without duplicating its fields.
Zod · Type Alias
z.infer extracts a static TypeScript type from a Zod schema. Use z.infer<typeof schema> to create a reusable alias that reflects the schema, including its output type when transformations are present.
z.infer is a TypeScript utility type that extracts the static type represented by a Zod schema. Apply it with typeof to a schema value, then reuse the resulting alias for compile-time checks; for transformed schemas, it corresponds to the schema's output type.
type Inferred = z.infer<typeof schema>;| Name | Type | Description |
|---|---|---|
schema | typeof Schema | The Zod schema value whose static TypeScript type should be extracted. |
The static TypeScript type inferred from the supplied Zod schema; for transformed schemas, this is the output type.
typeof, as in z.infer<typeof Player>.z.infer<typeof schema> is equivalent to the schema's output type.import { z } from "zod";
const Player = z.object({
username: z.string(),
xp: z.number(),
});
type Player = z.infer<typeof Player>;
const player: Player = { username: "billie", xp: 100 };
console.log(player);The type alias is inferred from the object schema, so the variable must have a string username and numeric xp.
Define a TypeScript type from an object schema without duplicating its fields.
Type variables or function inputs according to a schema's declared structure.
Represent the result of a schema that transforms parsed data.
z.infer do, and why is typeof used?z.infer<typeof Schema> derives a static TypeScript type from the schema value Schema. The schema is written first, and the alias stays synchronized with its declared structure.
Follow-up: How do you obtain the pre-transformation type? Use z.input<typeof Schema>; z.infer<typeof Schema> corresponds to the output type.
z.infer produce for an object schema?For an object schema containing username: z.string() and xp: z.number(), z.infer<typeof Player> produces a type requiring a string username and numeric xp. Assignments are then checked by TypeScript at compile time.
Follow-up: What happens if a value has xp: "100"? It is rejected because the inferred property type is number, regardless of runtime parsing.
z.infer behave with transformed schemas?A schema with a transform can have different input and output types. z.infer<typeof mySchema> is equivalent to z.output<typeof mySchema>, while z.input<typeof mySchema> describes the input.
Follow-up: For a string-to-length transform, what are the two types? The input is string, and the output is number.
z.inputz.outputz.objectz.stringz.number