TypeScript · Lesson 82 of 120
Validating Data
Runtime checks.
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.

- 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.
| key | value |
|---|---|
| Works | for small shapes |
| Problem | long and repetitive |
| Drift | type and check differ |
| Fix | a 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