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

Practice: An API Client

Fetch, validate, use.

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

Let's put it together. A small generic function that fetches a path, validates it with any Zod schema, and returns typed data, or a clear error.

Practice: An API Client
From the video: Practice: An API Client
  • Fetch
  • Validate
  • Typed result

A typed fetch helper

Fetch json takes a path and a schema. Its return type comes from the schema. Parse throws a clear error if the data is wrong. We load the bike list. Run it. Typed bikes, ready to use.

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

async function fetchJson<S extends z.ZodTypeAny>(path: string, schema: S): Promise<z.infer<S>> {
  return schema.parse(await get(path));
}

const Bike = z.object({ model: z.string(), price: z.number() });

const bikes = await fetchJson("/bikes", z.array(Bike));
for (const b of bikes) console.log(b.model, "£" + b.price.toFixed(2));
Output
Trail 500 £849.50
Volt 7 £2199.00
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

A generic helper that validates with Zod gives typed, trusted data from any API. Next, function overloads.

Key takeaways
  • fetchJson(path, schema)
  • z.infer<S>
  • Trusted data
Next up: Function Overloads — several signatures