Validating external data
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.
The gap
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
- Treat external data as
unknown(notany, and notas SomeType). - Validate it once, where it enters your program.
- 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):
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.
npm install zodimport { 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
const data: unknown = await response.json();
const user = User.parse(data); // returns a User, or throws a ZodErrorparse 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:
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:
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 numberz.prettifyError(result.error) formats all issues into one readable string.
Transforming while validating
Schemas can also clean data up:
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:
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; // numberA typed fetch helper
Combining it all — fetch as unknown, validate with a schema passed in:
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
ason external data is a guess. Parseunknowndata with a schema at the boundary, and letz.infergive you a type that can’t drift from the check.
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.
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" }];import { z } from "zod";
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
// Task schema and type
const Task = z.object({
id: z.number().int().positive(),
title: z.string().trim().min(1).max(100),
done: z.boolean().default(false),
tags: z.array(z.string()).default([]),
due: z.iso.date().optional(),
});
type Task = z.infer<typeof Task>;
// parseTasks
function parseTasks(json: string): Result<Task[], string[]> {
let data: unknown;
try {
data = JSON.parse(json);
} catch {
return { ok: false, error: ["body is not valid JSON"] };
}
const result = z.array(Task).safeParse(data);
if (!result.success) {
return { ok: false, error: result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`) };
}
return { ok: true, value: result.data };
}
// Env schema
const Env = z.object({
PORT: z.coerce.number().int().default(3000),
NODE_ENV: z.enum(["development", "production"]),
});
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" }];
for (const payload of payloads) {
const result = parseTasks(payload);
if (result.ok) {
for (const task of result.value) {
console.log(`#${task.id} "${task.title}" done=${task.done} tags=${task.tags.join("|")}`);
}
} else {
console.log("Rejected:", result.error.join("; "));
}
}
for (const env of envs) {
const parsed = Env.safeParse(env);
console.log(parsed.success ? parsed.data : `Invalid env: ${parsed.error.issues[0]?.message}`);
}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
unknownand 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
safeParseto handle invalid data as a normal result, and transform/coerce values (trim, defaults, numbers from strings) while validating.