Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Concepts and Comparisons

Runtime validation in TypeScript

Why TypeScript types cannot check JSON, form or API data, and how to validate at run time with type guards, hand-made schemas and schema libraries.

TypeScript checks your program before it runs. Once it runs, every type is gone (see Type erasure). That is fine for values your own code creates, but data that arrives from outside, such as a parsed JSON body, a form submission, an environment variable or a message from a queue, is only as trustworthy as its sender. JSON.parse returns any, and writing as User after it does not check anything: it just tells the compiler to stop worrying.

Runtime validation closes the gap. You write a check that inspects the real value, and the check tells the compiler what it learned, usually through a type predicate. After the check, the type is justified by evidence rather than by hope.

TypeScript
function isUser(value: unknown): value is { name: string } {
  return typeof value === "object" && value !== null &&
    typeof (value as { name?: unknown }).name === "string";
}

Try it

TypeScript A hand-written guard at the boundary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript A tiny schema that also gives you the type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Where to validate

Validate at every trust boundary, once, as close to the entry point as possible:

  • HTTP request bodies, query strings and headers.
  • Responses from other services, even your own.
  • JSON.parse results, files read from disk, localStorage contents.
  • process.env values (they are always string | undefined).
  • Messages from queues, WebSockets and postMessage.

Inside the boundary, pass the validated value around as a normal typed value and do not check it again.

Approaches compared

Approach Strength Weakness
Hand-written guard No dependency, full control Type and check can drift apart
Schema first (Zod, Valibot, ArkType and similar) One definition gives both the check and the type A dependency and some bundle size
Type first (generate checks from types) Types stay the source of truth Needs a build step or code generator
Schema from an API description (OpenAPI, JSON Schema) Shared with other languages Generated code to maintain

The second example above shows the schema-first idea in miniature: the type is derived from the parser with ReturnType, so the two cannot disagree.

Usage notes

  • Parse, do not just check. Good validators also convert: trim strings, turn date text into Date, apply defaults. The output type can differ from the input.
  • Validate unknown, not any. Declare the incoming value as unknown so the compiler forces you through the check. See any versus unknown.
  • Collect all errors for user-facing input. Throwing on the first problem is fine for internal data, but forms should report every failing field.
  • Extra properties: a guard like isUser accepts objects with additional fields. Decide whether to keep, strip or reject them.
  • Hand-written guards can lie. A type predicate is trusted blindly; if the body is wrong, the type is wrong. Test them.
  • as is not validation. See Type assertions.