Model validated objects
Keep a TypeScript alias synchronized with an object schema instead of duplicating its fields.
Zod · Type Alias
z.infer derives a static TypeScript type from a Zod schema. Use z.infer<typeof schema> to create a reusable type alias that stays aligned with the schema definition.
z.infer is a TypeScript utility type that derives a static type from a Zod schema. Apply it to the schema value with typeof, then reuse the resulting alias for compile-time checks alongside the runtime schema.
z.infer<typeof schemaName>| Name | Type | Description |
|---|---|---|
T | Zod schema type | A Zod schema type, supplied as a type argument using typeof schemaName. |
The static TypeScript type inferred from the supplied Zod schema.
z.infer utility to expose the schema's inferred type for annotations and other TypeScript type positions.typeof.typeof applied to the schema identifier.typeof; z.infer is a type-level utility, not a runtime function.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 schema remains the runtime validator, while z.infer derives the matching TypeScript type for static checking.
Keep a TypeScript alias synchronized with an object schema instead of duplicating its fields.
Annotate variables or function inputs with the exact type represented by a schema.
Use one schema for runtime validation and its inferred alias for compile-time checking.
Write type Player = z.infer<typeof Player>. The schema supplies runtime validation, and the alias supplies the corresponding static TypeScript type.
Follow-up: How would you infer the type of a schema named A? Use type A = z.infer<typeof A>; the typeof refers to the schema value.
z.infer extracts the static type represented by a schema definition. For an object schema with string and number fields, the resulting type has matching properties and types.
Follow-up: What does the schema still provide after inference? Runtime parsing and validation; type inference alone does not validate runtime input.
The inferred alias can annotate variables so TypeScript checks assignments against the schema's shape. The documentation demonstrates assigning an object with username and xp to the inferred type.
Follow-up: Why keep both the schema and alias? The schema handles runtime data, while the alias avoids duplicating the static type declaration.
z.objectz.stringz.numberZod schema definitions