Sub topic 4
One source of truth: deriving types with z.infer
Writing a TypeScript type and a validation rule for the same data means maintaining two descriptions of one shape. This chapter shows how z.infer removes the second description. You write the schema once and let the compiler derive the type from it.
This chapter assumes you can read TypeScript type aliases, interfaces, and generics at a basic level. It also assumes you can import npm packages and have read the previous chapter on z.object. You need zod installed and "strict": true in your tsconfig.json.
The problem: two descriptions of one shape
Without inference, a typical project has a hand-written type and a separate validator.
interface User {
id: number;
name: string;
nickname?: string;
}
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
typeof (value as User).id === "number" &&
typeof (value as User).name === "string"
);
}Nothing connects the interface to isUser. If someone adds email: string to the interface and forgets the function, the compiler stays silent. The guard now says "this is a User" about objects that have no email. The type and the check have drifted apart, and the type system trusts the guard.
A Zod schema can play both roles. It is a runtime value that checks data, and it carries enough type information for TypeScript to compute the matching static type.
Deriving a type with z.infer
z.infer takes the type of a schema and returns the type of the data that schema accepts.
import { z } from "zod";
const User = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
nickname: z.string().optional(),
});
type User = z.infer<typeof User>;
// { id: number; name: string; nickname?: string | undefined }Two parts of this deserve attention.
typeof Useris a TypeScript type query. It refers to the type of the variableUser, which is a Zod schema object type. It is not the type of the data.z.infer<...>unwraps that schema type and returns the type it parses to.
Checks such as .int(), .positive(), and .min(1) do not appear in the inferred type. TypeScript has no type for "positive integer", so id is just number. Those rules exist only at runtime, which is why you still need to parse the data.
One name for a value and a type
The example declares const User and type User with the same name. TypeScript allows this because values and types live in separate namespaces. In expression positions, User means the schema. In type positions, it means the inferred type.
function greet(user: User): string {
return `Hello, ${user.nickname ?? user.name}`;
}
const parsed = User.parse({ id: 1, name: "Ada" });
console.log(greet(parsed));The parameter annotation user: User uses the type. The call User.parse(...) uses the value. Many codebases follow this convention, so one import brings in both. Some teams prefer a suffix such as UserSchema for the value and User for the type. Either works. Choose one convention and apply it everywhere.
When you export, export both under the same name.
// user.ts
import { z } from "zod";
export const User = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
});
export type User = z.infer<typeof User>;Another file can then write import { User } from "./user" and use it as a type, a value, or both.
How the derivation works
z.infer is purely a compile-time feature. The compiler erases the type alias, so the compiled JavaScript contains only the schema. z.infer<typeof User> costs nothing at runtime.
Each Zod schema class carries a type parameter for the type it produces. z.string() produces string. z.number() produces number. z.object({...}) collects the types of its fields into an object type. .optional() wraps a field so that the key becomes optional and its value may be undefined. Each method returns a new schema whose type reflects the change.
The next diagram shows the two paths that start from one schema.
Because both paths start at the same schema, the type of the validated value cannot disagree with the schema's rules about its shape.
What gets inferred
The table lists common schemas and the types they infer to.
| Schema | Inferred type | Column |
|---|---|---|
| `z.string()` | `string` | |
| `z.number()` | `number` | |
| `z.boolean()` | `boolean` | |
| `z.string().optional()` | `string \ | undefined` |
| `z.string().nullable()` | `string \ | null` |
| `z.array(z.number())` | `number[]` | |
| `z.enum(["a", "b"])` | `"a" \ | "b"` |
| `z.literal("click")` | `"click"` |
Later chapters cover optional, nullable, arrays, and enums in detail. For now, notice that the inference follows the same rules you would use when writing the type by hand.
Inferring from nested and composed schemas
Inference works at any depth. You can infer the type of the whole schema, then pull out parts with indexed access types.
import { z } from "zod";
const Order = z.object({
id: z.string(),
customer: z.object({
name: z.string(),
email: z.string(),
}),
items: z.array(
z.object({
sku: z.string(),
quantity: z.number().int().positive(),
}),
),
});
type Order = z.infer<typeof Order>;
type Customer = Order["customer"];
type OrderItem = Order["items"][number];
function totalQuantity(items: OrderItem[]): number {
return items.reduce((sum, item) => sum + item.quantity, 0);
}Order["items"][number] reads as "the element type of the items array". You get named types for the pieces without declaring a separate schema for each one. If you reuse a sub-shape in several places, define it as its own schema instead. A later chapter covers composition with extend, pick, omit, and partial. Types inferred from composed schemas follow the composed shape automatically.
Common errors
Casting instead of parsing
The most frequent mistake is to declare the type and then assert it.
const data = JSON.parse(text) as User; // compiles, validates nothingThe as keyword tells the compiler to trust you. No check runs. The inferred type is only useful when the value really came through the schema.
const data: User = User.parse(JSON.parse(text)); // checked at runtimeForgetting typeof
Writing z.infer<User> fails because User is a value, not a type. The type argument must be typeof User.
Working without strict mode
Zod relies on strictNullChecks. Without "strict": true, optional fields and undefined handling are inferred incorrectly. Enable strict mode before you debug odd inferred types.
Treating the inferred type as the input type
z.infer returns what the schema produces after parsing. For plain schemas such as the ones in this chapter, the data going in and the data coming out have the same shape. Once a schema transforms or defaults values, the accepted type and the produced type can differ. A later chapter introduces z.input and z.output for exactly this case. In current Zod, z.infer is an alias for the output type.
Practical guidelines
- Define the schema first, then derive the type. Never go the other way for data that crosses a trust boundary.
- Keep the schema and its inferred type in the same module, and export both under one name.
- Use
import typewhen a file only needs the type and not the schema. The compiler then drops the import, and the runtime code never loads Zod for that file. - Do not derive the type from a parsed value with
typeof value. Derive it from the schema, so the type exists even where no value is available.
Exercise
A teammate writes const user = JSON.parse(body) as User; where User is z.infer<typeof User>, and says the data is now validated because the type comes from the schema. What is wrong, and how do you fix it?
Show answer
The as assertion only silences the compiler. Nothing checks body at runtime, so malformed data still flows through typed as User. The type comes from the schema, but the value never passed through it. Fix it by parsing: const user = User.parse(JSON.parse(body));, or by using safeParse when you want to handle failures without throwing.
Exercise
Given const Product = z.object({ sku: z.string(), tags: z.array(z.string()), price: z.number().positive() });, write the type alias that gives the type of a single entry in tags, derived from the schema.
Show answer
First infer the object type, then index into it: type Product = z.infer<typeof Product>; type Tag = Product["tags"][number];. Tag is string. The .positive() rule on price is not part of any inferred type, because TypeScript has no type for positive numbers.