Sub topic 6
Deriving TypeScript types with z.infer
This chapter assumes you know React function components and hooks, TypeScript generics and type aliases, and the basics of a Zod object schema. You do not need zodResolver yet. That comes in a later chapter. Here the goal is narrower: write the rules for your data once, and get the TypeScript type from them for free.
The problem: two sources of truth
A form needs two descriptions of its data. At runtime, something has to check that an email is non-empty and a password is long enough. At compile time, TypeScript has to know that the form values have an email string and a password string.
Without Zod, you write both by hand:
type SignUpValues = {
email: string;
password: string;
};
function validate(values: SignUpValues) {
// hand-written runtime checks
}Nothing forces the type and the checks to agree. Add a username field to the type and forget the check, and the compiler stays quiet. The two drift apart.
z.infer removes the duplication. The Zod schema is the single source of truth, and TypeScript computes the type from it.
Using z.infer
z.infer<typeof schema> takes the type of a schema value and returns the type of the data that schema produces.
import { z } from "zod";
const signUpSchema = z.object({
email: z.string().min(1, "Email is required").email("Enter a valid email"),
password: z.string().min(8, "Use at least 8 characters"),
});
type SignUpValues = z.infer<typeof signUpSchema>;
// { email: string; password: string }Two details matter here.
typeof signUpSchemais the TypeScripttypeofoperator. It turns the schema value into a type.z.inferthen reads that type.SignUpValuesexists only at compile time. It disappears when TypeScript is compiled. The schema stays, because it is a real JavaScript object that runs in the browser.
Validation rules such as .min(8) and .email() do not appear in the type. TypeScript has no type for "a string of at least 8 characters", so the inferred type is plain string. The schema enforces the rule at runtime. The type only describes the shape.
Passing the type to useForm
Pass the inferred type as the generic argument of useForm. React Hook Form then checks every field name you give to register, setError, getValues, and the other helpers.
import { useForm } from "react-hook-form";
import { z } from "zod";
const signUpSchema = z.object({
email: z.string().min(1, "Email is required").email("Enter a valid email"),
password: z.string().min(8, "Use at least 8 characters"),
});
type SignUpValues = z.infer<typeof signUpSchema>;
export function Example() {
const { register, setError } = useForm<SignUpValues>({
defaultValues: { email: "", password: "" },
});
register("email"K
// register("emial"); // compile error: not a field of SignUpValues
setError("email", { type: "server", message: "Already registered" });
return null;
}A typo in a field name now fails at compile time instently registering a field that the schema does not know about. The defaultValues object is also checked against the type. React Hook Form accepts partial defaults, but any key you do supply must have the right type.
If you rename email to emailAddress in the schema, TypeScript flags every register("email") and every errors.email in the project. The schema drives the refactor.
What the inferred type looks like for common schemas
The inferred type follows the schema closely. This table shows the mappings you meet most often in forms.
| Schema | Inferred type | Column |
|---|---|---|
| `z.string()` | `string` | |
| `z.number()` | `number` | |
| `z.boolean()` | `boolean` | |
| `z.string().optional()` | `string \ | undefined` |
| `z.string().nullable()` | `string \ | null` |
| `z.enum(["free", "pro"])` | `"free" \ | "pro"` |
| `z.array(z.string())` | `string[]` | |
| `z.object({ a: z.string() })` | `{ a: string }` | |
| `z.date()` | `Date` |
Optional fields are the most useful case to watch. A key marked .optional() becomes an optional property (a?: string | undefined). That affects how you write defaultValues and how you read values in onSubmit.
Nested objects and reusing pieces
Large forms are easier to manage when you build the schema from smaller schemas. The inferred type composes the same way.
import { z } from "zod";
const addressSchema = z.object({
street: z.string().min(1, "Street is required"),
city: z.string().min(1, "City is required"),
});
const profileSchema = z.object({
name: z.string().min(1, "Name is required"),
plan: z.enum(["free", "pro"]),
address: addressSchema,
});
type Address = z.infer<typeof addressSchema>;
type Profile = z.infer<typeof profileSchema>;
// Profile = { name: string; plan: "free" | "pro"; address: Address }With a nested type, register accepts dotted paths. register("address.city") type-checks, and register("address.town") does not. Error objects nest the same way, so the message lives at errors.address?.city?.message.
You can also derive related schemas without retyping fields. schema.pick, schema.omit, and schema.partial return new schemas, and z.infer works on each result.
import { z } from "zod";
const userSchema = z.object({
id: z.string(),
email: z.string().email(),
password: z.string().min(8),
});
const loginSchema = userSchema.pick({ email: true, password: true });
type LoginValues = z.infer<typeof loginSchema>;
// { email: string; password: string }Where the derivation flows
The diagram shows the direction of the dependency. Everything points away from the schema.
Common errors
Using the schema where a type is expected
useForm<signUpSchema> is an error. signUpSchema is a value, not a type. Write useForm<z.infer<typeof signUpSchema>>, or give the inferred type a name and use that.
Expecting rules to appear in the type
The type says string, not "email" or "at least 8 characters". Do not rely on the type to prove a value was validated. Only a successful parse or a passing submit proves that.
Optional fields and empty inputs
An HTML input never produces undefined. An empty text input gives "". If your schema says z.string().optional(), an empty input still passes as "", and the value is not undefined. If you want empty to mean absent, handle it in the schema or convert it before sending. Setting defaultValues for every field also keeps inputs from switching between uncontrolled and controlled.
Transforms change the output type
z.infer returns the schema's output type. For schemas without transforms, input and output match, so this rarely matters. Once you add .transform(Number), the inferred type has number where the input field holds a string. A later chapter covers z.input and z.output for this case. For now, remember that z.infer is the same as z.output.
Inference needs strict mode
Zod's type inference relies on TypeScript's strict option. With strict off, optional and required keys are not distinguished reliably and types can collapse to loose shapes. Keep "strict": true in tsconfig.json.
Where to keep the type
Define the schema and its type together, and export both. Other files then import one place.
// schemas/sign-up.ts
import { z } from "zod";
export const signUpSchema = z.object({
email: z.string().min(1, "Email is required").email("Enter a valid email"),
password: z.string().min(8, "Use at least 8 characters"),
});
export type SignUpValues = z.infer<typeof signUpSchema>;TypeScript lets a value and a type share one name, so some projects export const SignUp and type SignUp together. Separate names such as signUpSchema and SignUpValues are clearer for readers and work the same way.
Exercises
Exercise
A schema declares age: z.number().min(18). What is the type of age in z.infer<typeof schema>, and does the type guarantee the value is at least 18?
Show answer
The type is number. It does not guarantee the value is at least 18. The .min(18) rule runs only at runtime when the schema validates the data. TypeScript has no type for "a number of at least 18".
Exercise
Given const schema = z.object({ name: z.string(), nickname: z.string().optional() }), write the type alias for the inferred type and say what type values.nickname has.
Show answer
type Values = z.infer<typeof schema>; The type of values.nickname is string | undefined, and the property is optional (nickname?: string | undefined).
Exercise
You change a schema key from email to emailAddress. Why does TypeScript report errors in components that call register("email"), and what makes that possible?
Show answer
The form uses useForm<z.infer<typeof schema>>, so the field names come from the schema. After the rename, "email" is no longer a valid path, and register rejects it at compile time. The type is derived from the schema, so it updates automatically.