TypeScript in Practice

TypeScript in real projects · Lesson 8 of 12 · 15 min

Validating API data with Zod

Types disappear at runtime. When data comes from an API, a form or localStorage, TypeScript has to trust you. Zod checks it for real and gives you the type at the same time.

import { z } from "zod";
 
const User = z.object({
  id: z.string(),
  name: z.string().min(1),
  email: z.string().email(),
  plan: z.enum(["free", "pro"]),
});
 
type User = z.infer<typeof User>; // the type, derived from the schema

Parse at the edge

export async function getUser(id: string): Promise<User> {
  const res = await fetch(`/api/users/${id}`);
  return User.parse(await res.json()); // throws if the API sends something else
}

After this line, the rest of your app can trust the data completely.

Use safeParse when invalid data is expected, like form input: it returns { success, data, error } instead of throwing.

Exercise: write a schema for the /api/orders response in the starter project, then delete the hand-written Order type and use z.infer instead.