diff --git a/README.md b/README.md index a3c888695..e92c4464c 100644 --- a/README.md +++ b/README.md @@ -661,6 +661,32 @@ type User = z.infer; // { username: string } ``` +Validating an API response: + +```ts +import { z } from "zod"; + +const userSchema = z.object({ + id: z.number(), + username: z.string(), + email: z.string().email(), +}); + +type User = z.infer; + +async function getUserById(id: number) { + const response = await fetch(`/api/users/${id}`); + // data is untyped JSON response from the API + const data = await response.json(); + + // parse and validate the data against the schema to ensure it matches the expected shape + const user = userSchema.parse(data); + + // user is now fully typed as { id: number, username: string, email: string } + return user; +} +``` + ## Primitives ```ts