Explain it simply
Runtime validation in plain language
TypeScript types are like a 'staff only' sign on a door: they help your own team follow the rules, but they cannot physically stop a stranger. When the code runs, the types are gone, so data that arrives from a server, a file or a user needs a guard at the door who actually checks it.
Runtime validation is that guard: a small piece of code that really inspects the shape of the data. Only after it passes does the data enter your program as a typed value. In async code the check happens inside a promise, so you also need to catch its errors correctly.
Problem → Why → Solution
The problem: an annotation nobody checks
A dashboard calls GET /api/user and annotates the result as User. Months later the backend renames name to fullName. The frontend still compiles, every test with mocked data still passes, and in production the header shows "Hello, undefined" or crashes when it calls user.name.toUpperCase(). Nothing warned you, because the annotation was a promise nobody checked.
type User = { id: string; name: string };
async function loadUser(): Promise<User> {
const response = await fetch("/api/user");
const user: User = await response.json(); // any -> User, never checked
return user;
}
// The server now sends { id: "u1", fullName: "Ada" }
const user = await loadUser();
console.log(user.name.toUpperCase()); // TypeError at runtimeWhy this is dangerous
The annotation on response.json() is not a check; it turns any into User by assertion. TypeScript cannot see the network, so only code that runs can confirm the shape. Validating at the boundary turns a mysterious crash deep in the UI into a clear 'Invalid user response' error at the exact place the bad data entered.
Core concept: parse at the edge, then let typed data flow inward
TypeScript types exist only while you compile. The JavaScript that runs has no idea what User means, so nothing at runtime stops a server from sending { id: 42 } or an HTML error page. Anything that crosses into your program from outside, such as a fetch response, JSON.parse, localStorage, a form, a message queue or process.env, should be treated as unknown until code has checked it.
response.json() is typed as Promise<any> in the standard DOM types, which is why const user: User = await response.json() compiles without complaint: any is assignable to everything. Annotate the result as unknown instead. unknown forces you to narrow before use, and the place where you narrow becomes your validation boundary. Also remember that fetch only rejects on network failure; a 404 or 500 still resolves, so check response.ok before reading the body.
An async function always returns a Promise. A throw inside it becomes a rejected promise, and the caller only sees that error if it awaits the call inside try/catch (or attaches .catch). Under strict mode the catch variable is unknown (the useUnknownInCatchVariables option), because JavaScript can throw anything, not just Error objects; narrow it with error instanceof Error before reading message.
| Source | Typed as | What to do |
|---|---|---|
| response.json() | Promise<any> | annotate as unknown, then validate |
| JSON.parse(text) | any | annotate as unknown, then validate |
| catch (error) | unknown (strict) | narrow with instanceof Error |
There are two common ways to validate. A handwritten type guard (value is User) has no dependencies and suits small shapes. A schema library such as zod describes the shape once, checks it at runtime and derives the static type with z.infer, so the check and the type cannot drift apart. Either way the rule is the same: parse at the edge, then let typed data flow inward.
- Outside data arrives as unknown
- Check status, then parse the body
- Validate with a guard or schema
- Only validated data gets a type
The compiler trusts your types; validation is what makes them true at runtime.
General pattern
async function loadThing(url: string): Promise<Thing> {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data: unknown = await response.json();
if (!isThing(data)) throw new Error("Invalid response");
return data; // narrowed to Thing by the guard
}Check the HTTP status first, parse the body as unknown, validate it with a guard or schema, and only then return it. On failure, throw an error with a clear message.
Worked example: loading a user with a type guard
So that it runs in Node without a network, fakeFetch builds a real Response object; everything else is the same as real fetch code. main tries one valid body, one body with the wrong shape and one HTTP 500.
type User = { id: string; name: string };
function isUser(value: unknown): value is User {
if (typeof value !== "object" || value === null) return false;
const record = value as Record<string, unknown>;
return typeof record.id === "string" && typeof record.name === "string";
}
// A stand-in for fetch so the example runs offline in Node
async function fakeFetch(body: string, status = 200): Promise<Response> {
return new Response(body, { status });
}
async function loadUser(body: string, status?: number): Promise<User> {
const response = await fakeFetch(body, status);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const value: unknown = await response.json();
if (!isUser(value)) throw new Error("Invalid user response");
return value;
}
async function main() {
const user = await loadUser('{"id":"u1","name":"Ada"}');
console.log("ok:", user.name);
for (const [body, status] of [['{"id":42}', 200], ["{}", 500]] as const) {
try {
await loadUser(body, status);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.log("rejected:", message);
}
}
}
main();Code breakdown
- The type guard
function isUser(value: unknown): value is User {Accepts unknown and returns the type predicate value is User. When it returns true, the compiler narrows value to User at the call site.
- Check the status
if (!response.ok) throw new Error(`HTTP ${response.status}`);fetch does not reject on a 500, so the code checks it itself and never feeds an error page to the parser.
- Parse as unknown
const value: unknown = await response.json();Annotating unknown instead of accepting any means value cannot be read from or returned until it passes the guard.
- Validate, then return
if (!isUser(value)) throw new Error("Invalid user response");After this line value is a User and can be returned as Promise<User>. A wrong shape throws right where the data entered.
- Catch and narrow
const message = error instanceof Error ? error.message : String(error);Because the await is inside try, the rejection is caught. error is unknown, so it is narrowed with instanceof Error before message is read.
ok: Ada
rejected: Invalid user response
rejected: HTTP 500Validating with a schema (zod)
As fields pile up, handwritten guards get long and easily drift from the type. With zod you write the schema once and derive the type from it. safeParse returns a result with a success flag instead of throwing, and error.issues lists the path of every failing field.
import { z } from "zod";
const UserSchema = z.object({
id: z.string(),
name: z.string().min(1),
age: z.number().int().nonnegative().optional(),
});
type User = z.infer<typeof UserSchema>; // inferred: id, name, optional age
function parseUser(data: unknown): User | null {
const result = UserSchema.safeParse(data);
if (!result.success) {
const paths = result.error.issues.map((issue) => issue.path.join("."));
console.log("invalid fields:", paths.join(", "));
return null;
}
return result.data;
}
console.log(parseUser({ id: "u1", name: "Ada", age: 36 }));
parseUser({ id: 7, name: "", age: -1 }); // prints: invalid fields: id, name, ageChange UserSchema and the User type follows, so the check and the type can no longer disagree. Use parse if you prefer throwing, but at a boundary safeParse makes it easier to turn the failure into a user-friendly message or an HTTP 400.
In real projects
Where to validate in real projects
Every production app has boundaries where untyped data enters. Typical places to validate:
- API clients: wrap fetch in one helper that checks response.ok, parses JSON as unknown and runs a schema, so no component ever touches raw JSON.
- Server handlers: validate request bodies and query strings before they reach business logic, and return a 400 with the failing field paths instead of a 500 from deep inside.
- Configuration: parse process.env once at startup with a schema, so a missing DATABASE_URL fails immediately with a clear message rather than on the first query.
- Stored data: localStorage, IndexedDB and queues may hold data written by an older version of your app; validate it and fall back to defaults when the shape has changed.
Common mistakes
Common mistakes with async code and validation
Casting JSON instead of validating it
(await response.json()) as User is the same as annotating it as User: an assertion that compiles and checks nothing. Use unknown plus a guard or a schema.
Forgetting that fetch does not reject on HTTP errors
A 404 page or an { error } body will reach your parser. Check response.ok (or response.status) first and turn it into a meaningful error.
Not awaiting inside try/catch
try { loadUser(); } catch {} catches nothing, because the promise rejects later. Write await loadUser() inside the try, or the error becomes an unhandled rejection.
Reading error.message without narrowing
In strict mode the error in a catch clause is unknown, so error.message is a compile error. Check error instanceof Error first and fall back to String(error).
Best practices
Best practices
- Keep validation in one place per boundary, then let the rest of the app trust the typed data.
- Put the endpoint and the failing field into error messages, so problems are easy to find in production logs.
- For expected failures that every caller must handle, return a discriminated union such as { ok: true } | { ok: false } instead of throwing.
Mini challenge
Mini challenge: a loadProducts that never throws
Write loadProducts for a shop page. It receives a function that fetches JSON (so you can test it without a network), validates the data with zod and returns a result object instead of throwing, so the page can show either the products or an error message.
- Define ProductSchema with zod and derive type Product with z.infer
- Return { ok: true; products } on success and { ok: false; error } on failure
- Turn both a thrown error and invalid data into { ok: false }
- Run it with a valid payload, an invalid payload and a failing service, and print each outcome
import { z } from "zod";
// TODO: id (string), name (non-empty string), price (number >= 0)
const ProductSchema = z.object({});
type Product = z.infer<typeof ProductSchema>;
type LoadResult =
| { ok: true; products: Product[] }
| { ok: false; error: string };
async function loadProducts(getJson: () => Promise<unknown>): Promise<LoadResult> {
// TODO: await getJson() inside try/catch and narrow the error
// TODO: validate an array of products with safeParse
// TODO: return the matching LoadResult
}
// TODO: call loadProducts with fake getJson functions and print each resultExpected: The valid payload prints 1 product(s), the payload with price: -1 prints Invalid data at 0.price, and the throwing getJson prints Service unavailable.
Show hint
Check the whole array with z.array(ProductSchema).safeParse(data). Putting issue.path.join(".") into the error message shows which field of which item failed. A fake getJson can be written as async () => [...].
Show solution
import { z } from "zod";
const ProductSchema = z.object({
id: z.string(),
name: z.string().min(1),
price: z.number().nonnegative(),
});
type Product = z.infer<typeof ProductSchema>;
type LoadResult =
| { ok: true; products: Product[] }
| { ok: false; error: string };
async function loadProducts(getJson: () => Promise<unknown>): Promise<LoadResult> {
let data: unknown;
try {
data = await getJson();
} catch (error) {
const message = error instanceof Error ? error.message : "Network error";
return { ok: false, error: message };
}
const parsed = z.array(ProductSchema).safeParse(data);
if (!parsed.success) {
const where = parsed.error.issues.map((issue) => issue.path.join(".")).join(", ");
return { ok: false, error: `Invalid data at ${where}` };
}
return { ok: true, products: parsed.data };
}
async function main() {
const good = await loadProducts(async () => [{ id: "p1", name: "Pen", price: 2.5 }]);
const bad = await loadProducts(async () => [{ id: "p2", name: "Ink", price: -1 }]);
const down = await loadProducts(async () => {
throw new Error("Service unavailable");
});
for (const result of [good, bad, down]) {
console.log(result.ok ? `${result.products.length} product(s)` : result.error);
}
}
main();Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Types are erased at runtime, so treat outside data as unknown until it is validated.
- response.json() and JSON.parse return any; an annotation or an as cast is not a check.
- Use a type guard for small shapes, or a zod schema with z.infer so the check and the type share one source.
- Check response.ok, await inside try, and narrow the unknown catch variable with instanceof Error.
Narrowing — TypeScript