Sub topic 6
Deriving TypeScript types with z.infer
This chapter assumes you know React function components and hooks, TypeScript types and generics, and the basics of a Zod object schema. You will learn how to get a TypeScript type from a schema instead of writing it by hand.
The problem: two sources of truth
Suppose you write a validation rule and a type separately:
interface SignUpValues {
email: string;
password: string;
}Later you add a name field to the validation code but forget the interface. TypeScript does not warn you, because the two are unrelated. The form compiles, and the data is wrong at runtime.
Zod solves this by keeping one definition. The schema is a runtime value, and z.infer reads its shape at compile time and produces a type.
Using z.infer
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:
signUpSchemais a value, so you needtypeof signUpSchemato turn it into a type before passing it toz.infer.- Error messages such as
"Use at least 8 characters"exist only at runtime. They do not change the inferred type.
Rules like min(8) also do not narrow the type. A password is still a plain string. The type says what shape the data has. The schema says whether a specific value is acceptable.
Passing the type to useForm
Give the inferred type to useForm as its generic argument. Then register, errors, and handleSubmit all know your field names.
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
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 SignUpForm() {
const { register, handleSubmit } = useForm<SignUpValues>({
resolver: zodResolver
defaultValues: { email: "", password: "" },
});
const onSubmit = (values: SignUpValues) => {
console.log(values.email);
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("email")} />
<input type="password" {...register("password")} />
<button type="submit">Create account</button>
</form>
);
}Now register("emial") is a compdefaultValues must match the type, and values in onSubmit` is fully typed.
Common errors
- Writing
z.infer<signUpSchema>. This fails becausesignUpSchemais a value. Usetypeof signUpSchema. - Keeping a hand-written interface alongside the schema. The two drift apart. Derive the type and delete the interface.
- Expecting
z.inferto describe transformed data.z.inferreturns the output type. If a schema usestransform, the form's input values can differ from the inferred type. A later chapter covers this.
Exercise
Given const loginSchema = z.object({ username: z.string(), remember: z.boolean() }), write the line that creates a LoginValues type from it, and say what happens to the type if you later add age: z.number() to the schema.
Show answer
type LoginValues = z.infer<typeof loginSchema>; The type updates automatically to { username: string; remember: boolean; age: number }, so any code that builds a LoginValues without age becomes a compile error and shows you where to update.