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

Validating Data

Runtime checks.

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

Types vanish when the code runs. So to trust outside data, we check it while running. A function that checks the shape, and then narrows the type, gives us both safety and types.

Validating Data
From the video: Validating Data
  • Types vanish
  • Check while running
  • Safety and types

A hand-written check

Is order checks every field, and its return type narrows unknown to order. Bad data is rejected, before anything uses it. Run it. Order ten forty two passes, ten forty three fails.

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

type Order = { id: number; status: string; total: number };

function isOrder(x: unknown): x is Order {
  if (typeof x !== "object" || x === null) return false;
  const o = x as Record<string, unknown>;
  return typeof o.id === "number" && typeof o.status === "string" && typeof o.total === "number";
}

for (const id of [1042, 1043]) {
  const data = await get(`/orders/${id}`);
  console.log(id, isOrder(data) ? `valid, total £${data.total}` : "invalid data");
}
Output
1042 valid, total £65
1043 invalid data
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]);
}

The catch

Hand written checks get long, and can drift from the type. If someone adds a field to the type, the check doesn't know. That's why libraries like Zod exist.

keyvalue
Worksfor small shapes
Problemlong and repetitive
Drifttype and check differ
Fixa schema library

Summary

Check outside data while running, with a function that narrows the type. Next, Zod.

Key takeaways
  • x is Order
  • Runtime checks
  • Drift risk
Next up: Zod — schemas to types