Validating external data

Topic 3 of 3 in Async code and runtime safety8 min readIntermediateFree course

Overview

Everything so far has relied on TypeScript knowing your types. But types are erased before your code runs. When data arrives while the program runs — a JSON response, a form submission, a file, an environment variable — no type annotation can check it. This lesson shows the gap and the standard way to close it: validate at the boundary.

Types stop at the edge of your program. The outside world — API responses, request bodies, JSON and CSV files, localStorage, environment variables — provides unknown data. A validate step, such as Task.parse(data), checks every field at run time; invalid data produces a clear error. Inside your program the data is trusted and typed: task.title: string, task.done: boolean. TypeScript types are erased before the code runs, so they cannot check data that arrives while it runs. Validate at the boundary (with a schema library such as Zod, or a type guard); inside, the types can be trusted. A Zod schema gives you both: the run-time check and the TypeScript type (z.infer<typeof Task>).

The gap

TypeScript
type User = { id: number; name: string };

const response = await fetch("/api/users/1");
const user = (await response.json()) as User;   // "trust me"

console.log(user.name.toUpperCase());

This compiles. But if the API returns { "id": 1, "fullName": "Asha" } — a renamed field, a bug, a different version — user.name is undefined and the program crashes on a line TypeScript said was safe. The as User was a promise nobody checked.

The same applies to JSON.parse, localStorage.getItem, process.env, CSV rows, WebSocket messages, postMessage data and query strings.

The rule: unknown in, validated out

  1. Treat external data as unknown (not any, and not as SomeType).
  2. Validate it once, where it enters your program.
  3. From then on, the data has a real, checked type, and the rest of the code can trust it.

You’ve seen the hand-written way already — a type guard (Custom type guards):

TypeScript
function isUser(value: unknown): value is User {
  return (
    typeof value === "object" && value !== null &&
    "id" in value && typeof value.id === "number" &&
    "name" in value && typeof value.name === "string"
  );
}

It works, but for real data — nested objects, arrays, optional fields, string formats, helpful error messages — guards become long, repetitive, and can silently disagree with the type they claim to check.

Schema validation with Zod

Zod is the most widely used TypeScript validation library. You describe the shape once, as a schema, and get two things from it: a run-time validator and the TypeScript type.

Terminal
npm install zod
TypeScript
import { z } from "zod";

const User = z.object({
  id: z.number().int().positive(),
  name: z.string().min(1),
  email: z.email(),
  role: z.enum(["admin", "editor", "viewer"]).default("viewer"),
  tags: z.array(z.string()).default([]),
});

type User = z.infer<typeof User>;
// { id: number; name: string; email: string; role: "admin" | "editor" | "viewer"; tags: string[] }

Because the type is inferred from the schema, the two can never disagree.

parse and safeParse

TypeScript
const data: unknown = await response.json();

const user = User.parse(data);        // returns a User, or throws a ZodError

parse is good when invalid data is truly unexpected. When invalid data is a normal outcome (user input), safeParse returns a discriminated union instead of throwing:

TypeScript
const result = User.safeParse(data);

if (result.success) {
  result.data.name;                   // User
} else {
  for (const issue of result.error.issues) {
    console.log(issue.path.join("."), issue.message);
  }
}

For { "id": -1, "name": "", "email": "nope", "tags": ["a", 7] }, the issues read like:

Text
id Too small: expected number to be >0
name Too small: expected string to have >=1 characters
email Invalid email address
tags.1 Invalid input: expected string, received number

z.prettifyError(result.error) formats all issues into one readable string.

Transforming while validating

Schemas can also clean data up:

TypeScript
const Signup = z.object({
  email: z.string().trim().toLowerCase().pipe(z.email()),   // clean first, then check the format
  name: z.string().trim().min(1),
  newsletter: z.boolean().default(false),
});

Signup.parse({ email: "  ASHA@Example.com ", name: " Asha " });
// { email: "asha@example.com", name: "Asha", newsletter: false }

Order matters: checks run where they appear, so z.email().trim() would reject " asha@example.com" before trimming it. .pipe() passes the cleaned string on to the next schema.

Environment variables

Every environment variable is a string | undefined. Validate them once at start-up and get a typed config object:

TypeScript
const Env = z.object({
  PORT: z.coerce.number().int().default(3000),     // "8080" → 8080
  DATABASE_URL: z.url(),
  NODE_ENV: z.enum(["development", "production", "test"]),
});

export const env = Env.parse(process.env);   // fail fast with a clear message if misconfigured
env.PORT;                                    // number

A typed fetch helper

Combining it all — fetch as unknown, validate with a schema passed in:

TypeScript
async function getJson<S extends z.ZodType>(url: string, schema: S): Promise<z.infer<S>> {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`);
  return schema.parse(await response.json());
}

const user = await getJson("/api/users/1", User);   // User — checked, not assumed
const users = await getJson("/api/users", z.array(User));

Alternatives

Zod isn’t the only option: Valibot (very small bundles), ArkType (type-syntax schemas) and others work similarly, and many support the shared Standard Schema interface, so frameworks accept any of them. For JSON APIs you control, OpenAPI tools can generate both types and validators. The principle is the same everywhere: one definition, a run-time check, a derived type.

Where to validate

  • Server: request bodies, query strings, route params, webhooks, environment variables, messages from queues.
  • Client: API responses (yes, even your own API — it may be a different version), localStorage, URL parameters.
  • Anywhere: files and data from other teams’ services.

Inside your program, after the boundary, don’t re-validate — trust the types. That’s the payoff: checks in one place, safety everywhere else.

Remember: an as on external data is a guess. Parse unknown data with a schema at the boundary, and let z.infer give you a type that can’t drift from the check.

Exercise

Validate an API payload with Zod

Install Zod (npm install zod). Define a Task schema: id (positive integer), title (string, 1–100 characters, trimmed), done (boolean, default false), tags (array of strings, default []) and due (optional, an ISO date string). Derive type Task = z.infer<typeof Task>. Write parseTasks(json: string): Result<Task[], string[]> that parses the JSON (catching syntax errors) and validates it with z.array(Task).safeParse, returning error messages like 1.title: Too small: expected string to have >=1 characters on failure. Also define an Env schema that coerces PORT to a number (default 3000) and requires NODE_ENV to be "development" or "production". Print results for the three payloads and two env objects in the starter.

TypeScript
import { z } from "zod";

type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };

// Task schema and type

// parseTasks

// Env schema

const payloads = [
  '[{"id": 1, "title": "  Write lesson  ", "tags": ["ts"]}, {"id": 2, "title": "Review", "done": true}]',
  '[{"id": 3, "title": "OK"}, {"id": -4, "title": ""}]',
  "{not json",
];
const envs = [{ PORT: "8080", NODE_ENV: "production" }, { NODE_ENV: "staging" }];

Summary

  • Types are erased, so they can’t check data that arrives at run time: JSON, API responses, forms, files, env vars.
  • Treat such data as unknown and validate it at the boundary; after that, the types can be trusted.
  • Type guards work for small shapes; schema libraries such as Zod scale to real data.
  • A Zod schema is both a run-time validator and a type: type Task = z.infer<typeof Task>.
  • Use safeParse to handle invalid data as a normal result, and transform/coerce values (trim, defaults, numbers from strings) while validating.