1. Concept library
  2. JavaScript & TypeScript
  3. Module 11: Errors and validation

Concept

Runtime validation

Types are gone at runtime, so data from a request, a file or local storage must be checked before it is used. A schema library such as zod validates and gives you the TypeScript type in one place.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain why types alone cannot protect code from data that arrives at runtime
  2. Write a zod schema and derive the TypeScript type from it
  3. Validate a request body at the boundary and report what was wrong

In practice

A few lines that show Runtime validation doing its job.

TypeScript
import { z } from "zod";

const User = z.object({
  id: z.string().uuid(),
  name: z.string().min(1),
  email: z.string().email().optional(),
});
type User = z.infer<typeof User>;

const parsed = User.safeParse(await res.json());
if (!parsed.success) throw new Error(parsed.error.message);
const user: User = parsed.data;

The common mistake

Watch for

Keeping an interface and a validator that describe the same shape separately. They drift apart, and the type then promises fields the validator never checked. Derive the type from the schema.

What to know first

Your roadmap puts these before Runtime validation, unless you already know them.

How it stays learned

Once a session shows you understand Runtime validation, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled
Previous in the module← The unknown type