How the types are generated
| JSON | TypeScript | Zod |
|---|---|---|
"text" | string | z.string() |
42 | number | z.number().int() |
4.8 | number | z.number() |
true | boolean | z.boolean() |
null | null | z.null() / .nullable() |
[…] | T[] | z.array(…) |
{…} | a named interface | a named z.object(…) |
| key missing in some array items | key?: | .optional() |
Validate API responses with Zod
Generate a schema from a real response, then parse every response through it:
import { ApiResponseSchema } from "./schemas";
const res = await fetch("https://api.example.com/v1/items/42");
const data = ApiResponseSchema.parse(await res.json()); // throws if the shape is wrong
// data is fully typed from here onNeed a response to start from? Pick any free API that needs no key, or convert its curl example with the cURL converter. Messy JSON? Clean it up first with the JSON formatter.