AI Hints
Home›TypeScript Tutorial›Validation and Zod
TypeScript · Lesson 83 of 120

Zod

Schemas to types.

⏱ 2 min read▶ Video at 1:04:48🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Zod lets you write a schema once. It checks data while running, and gives you a TypeScript type from the same schema. One source of truth.

Zod
From the video: Zod
  • One schema
  • Checks at runtime
  • Type for free

An order schema

The schema describes an order, with rules, like a positive total. Z dot infer gives the matching type. Safe parse checks data, and never throws. Run it. The good order passes, the bad one lists exactly what's wrong.

app.tstypescript
import { z } from "zod";
import { get } from "./shop-api.js";

const OrderSchema = z.object({
  id: z.number().int(),
  status: z.enum(["packing", "shipped", "delivered"]),
  total: z.number().positive(),
});
type Order = z.infer<typeof OrderSchema>;

for (const id of [1042, 1043]) {
  const result = OrderSchema.safeParse(await get(`/orders/${id}`));
  if (result.success) console.log(id, "ok, total", result.data.total);
  else console.log(id, "invalid:", result.error.issues.map(i => `${i.path} ${i.message}`));
}
Output
1042 ok, total 65
1043 invalid: [ 'total Expected number, received string' ]
Also uses shop-api.ts
const DATA: Record<string, unknown> = {
  "/bikes": [{ model: "Trail 500", price: 849.5 }, { model: "Volt 7", price: 2199 }],
  "/orders/1042": { id: 1042, status: "shipped", total: 65 },
  "/orders/1043": { id: 1043, status: "packing", total: "thirty" },
};

export async function get(path: string): Promise<unknown> {
  await new Promise(resolve => setTimeout(resolve, 100));   // pretend network delay
  if (!(path in DATA)) throw new Error(`404 Not Found: ${path}`);
  return structuredClone(DATA[path]);
}

Summary

Zod schemas check data at runtime, and produce types with z dot infer. Next, practice with an API client.

Key takeaways
  • z.object
  • z.infer
  • safeParse
Next up: Practice: An API Client — fetch, validate, use