Sub topic 4
One source of truth: deriving types with `z.infer`
Assume you know basic TypeScript types, interfaces, type aliases, JavaScript objects, and ES module imports. This chapter focuses on the connection between a Zod schema and the TypeScript type derived from it.
Why derive a type from a schema?
TypeScript types exist only while your code is being checked. They are removed when TypeScript compiles your program. A type cannot inspect data received from an API, form, file, or environment variable while the program runs.
A Zod schema exists at runtime. It can check that data has the expected shape. The schema can also produce a matching TypeScript type with z.infer.
This gives one definition for both jobs:
| Concern | Tool | When it works |
|---|---|---|
| Validate actual data | Zod schema | At runtime |
| Check code using validated data | TypeScript type | At compile time |
Without z.infer, you might define the same shape twice. Those definitions can drift apart. A field added to the schema might be missing from the interface, or an interface might claim that a field is required when the schema makes it optional.
Derive a type with `z.infer`
Define the schema first. Then pass the schema value to z.infer using typeof:
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>;
function welcome(user: User): string {
const nickname = user.nickname ?? user.name;
return `Welcome, ${nickname}!`;
}
const user = User.parse({
id: 42,
name: "Mina",
});
console.log(welcome(user));User with a capital letter is the schema value. User in the type declaration is a TypeScript type. They share a name, but they have different roles.
The inferred type is equivalent to:
type User = {
id: number;
name: string;
nickname?: string | undefined;
};The optional() call means the nickname property may be absent. It does not mean that every value is valid. If the property is present, it must be a string.
How inference follows the schema
Zod maps schema methods to TypeScript types:
z.string()becomesstring.z.number()becomesnumber.z.boolean()becomesboolean.z.array(z.string())becomesstring[].z.object({...})becomes an object type.z.literal("admin")becomes the literal type"admin".z.enum(["draft", "published"])becomes a union of those string literals.
Checks such as .min(1), .positive(), and .email() usually narrow runtime values without creating a narrower TypeScript type. For example, a positive integer is still represented as number in TypeScript.
Follow the schema, not a duplicate interface
When the expected shape changes, update the schema. The inferred type changes automatically:
const User = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
nickname: z.string().optional(),
role: z.enum(["member", "admin"]).default("member"),
});
type User = z.infer<typeof User>;Now validated users have a role value in the parsed result. Keeping the schema as the source of truth prevents validation and application code from silently disagreeing.
Exercise
What TypeScript type does z.object({ title: z.string(), tags: z.array(z.string()).optional() }) infer?
Show answer
It infers { title: string; tags?: string[] | undefined }.