Validate untrusted data at runtime in TypeScript

8 steps · about 2 h 6 min · Intermediate

  1. The unknown type and why it beats any (doc, TypeScript, 12 min)

    Start by seeing why data from outside your program should arrive as unknown: the compiler forces a check before you touch it.

  2. Assertion functions (doc, TypeScript, 12 min)

    Assertion functions let one checking call narrow a value for the rest of a block, the basic shape of a hand-written validator.

  3. Inferred type predicates (doc, TypeScript, 12 min)

    Read how filter callbacks and small checks now produce type predicates, and where a guard still needs an explicit return type.

  4. Zod: schemas that produce types (doc, Zod, 10 min)

    Once guards get long, a schema library keeps the runtime check and the static type in one definition; skim the introduction and install it.

  5. Parse, safeParse and inferred types (doc, Zod, 20 min)

    Practise parse versus safeParse and z.infer on a real API response so a bad payload becomes a handled result, not a crash later.

  6. Turn validation errors into useful messages (doc, Zod, 15 min)

    Format issues by field path so users see which input failed and logs show exactly which part of a payload was wrong.

  7. Describe the same data in JSON Schema (tutorial, JSON Schema, 25 min)

    JSON Schema is the language-neutral contract; writing one lets a back end in any language check the same shape you validate in the browser.

  8. Validate JSON Schema with Ajv in TypeScript (doc, Ajv, 20 min)

    Finish by compiling a schema with Ajv and getting a typed guard, so shared schemas from other teams are enforced in your code too.