Validating untrusted data at runtime
Types vanish at runtime, so API responses and form input need a real check. Schema libraries like Zod and Valibot validate data and infer the type.
Why TypeScript, and what a type checker doesany, unknown, never, and voidType guards and assertion functionsTyping asynchronous code
Validating untrusted data at runtime
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Type annotations are erased before code runs, so a type on data from a network call, a form, a file, or `localStorage` is a promise nobody checked.
- `res.json()` and `JSON.parse` return `any`, which assigns to any type silently; treat their results as `unknown` until something has checked them.
- A hand-written type guard works but duplicates the type in a second place, and the two drift apart when one changes and the other doesn't.
- A schema library such as Zod or Valibot lets you write the shape once as a runtime value; the library checks data against it and infers the static type with `z.infer` or `v.InferOutput`.
- `parse` throws on bad data and returns a typed value; `safeParse` returns a result you narrow on `success`, which suits form input where failure is expected.
- Validate once, at the boundary where data enters the program, and let the inferred type carry the guarantee inward.
The type that nobody checked
Here’s a function that looks fully typed:
type User = { id: number; email: string; roles: string[] };
async function loadUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
return res.json();
}
It compiles with no complaints. Now suppose the backend renames roles to permissions. The code still compiles, loadUser still claims to return a User, and the crash happens three files away when something calls user.roles.includes("admin").
The core problem is that types don’t exist at runtime. As the first lesson put it, the compiler erases them. It can check what your own code does with values, but it can’t check what a server, a form, a file, or localStorage will hand you. And res.json() returns Promise<any>, which assigns to anything without a word.
So every point where data enters the program is a gap in the type system. Closing it takes code that actually runs.
Start from unknown
The first fix is honesty. Treat outside data as unknown, which forces a check before use:
function isUser(value: unknown): value is User {
return (
typeof value === "object" && value !== null &&
"id" in value && typeof value.id === "number" &&
"email" in value && typeof value.email === "string" &&
"roles" in value && Array.isArray(value.roles) &&
value.roles.every((r) => typeof r === "string")
);
}
async function loadUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
const data: unknown = await res.json();
if (!isUser(data)) throw new Error("Unexpected response shape");
return data; // data: User
}
This is correct, and it uses only the type guards you already know. But look at what it costs. User is described twice: once as a type, once as a stack of runtime checks. Nothing ties them together. Add name: string to the type and the guard still compiles, still returns true for objects without a name, and the checker trusts it. For one type that’s manageable. For forty API responses it isn’t.
A schema: one definition, two outputs
Schema libraries flip the order. You describe the shape once, as an ordinary JavaScript value. The library walks that value to check data at runtime, and TypeScript reads the same value to infer the static type. Here it is in Zod:
import { z } from "zod";
const User = z.object({
id: z.number().int(),
email: z.email(),
roles: z.array(z.string()),
});
type User = z.infer<typeof User>;
// { id: number; email: string; roles: string[] }
async function loadUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
return User.parse(await res.json());
}
Using the same name for the schema and the type is a common convention, since one is a value and the other a type. Rename roles in the schema and both the check and the type change together. The schema can also say things a type can’t: that id is an integer, or that email looks like an address.
Think of it like a building’s blueprint. You don’t draw the floor plan once for the builders and again, freehand, for the inspector. Both work from the same drawing.
parse versus safeParse
parse returns typed data or throws a ZodError listing every problem. That suits data that should never be wrong, like your own config file, where failing loudly at startup is the right response.
Form input is different. Bad input is normal, and you want to show messages, not crash:
const result = User.safeParse(formData);
if (!result.success) {
console.log(result.error.issues); // [{ path: ["email"], message: "..." }, ...]
} else {
saveUser(result.data); // result.data: User
}
The result is a discriminated union on success, so narrowing gives you data in one branch and error in the other.
When input and output differ
Schemas can transform as they check. Query strings and form fields arrive as strings, so a schema can coerce:
const Query = z.object({ page: z.coerce.number().int().min(1) });
type QueryIn = z.input<typeof Query>; // { page: unknown }
type QueryOut = z.output<typeof Query>; // { page: number }
z.infer is the output side. When a schema transforms, name the side you mean.
Zod is not the only option
Valibot does the same job with standalone functions instead of method chains, so a bundler can drop the validators you don’t use:
import * as v from "valibot";
const User = v.object({
id: v.pipe(v.number(), v.integer()),
email: v.pipe(v.string(), v.email()),
roles: v.array(v.string()),
});
type User = v.InferOutput<typeof User>;
const user = v.parse(User, data);
ArkType is a third choice that writes schemas in a syntax close to TypeScript’s own. Zod, Valibot, and ArkType all implement Standard Schema, a shared interface, so form and routing libraries can accept a schema from any of them.
Validate at the edge, trust inside
Check data once, where it enters: the response handler, the form submit, the config loader, the message listener. After that the inferred type tells every function downstream that the data was checked, and internal code shouldn’t check it again. A schema can also mark that fact with a brand, as shown in branded types.
About the video
Austin Davis’s video, from early 2026, frames the same problem: types disappear at runtime, so API, form, and external data can’t be trusted. It then builds Zod schemas for primitives, objects, strict objects, and arrays, derives types with z.infer, and handles failures with safeParse. It was published after Zod 4 shipped, and the examples in this lesson follow Zod 4’s API. It doesn’t cover Valibot; Jack Herrington’s comparison in the links puts the two side by side.
Check yourself
Why doesn't `const user: User = await res.json();` protect you from a server that sends the wrong shape?
`res.json()` returns `Promise<any>`, and `any` is assignable to `User` without any check. The annotation is erased at compile time, so at runtime nothing compares the response to `User`. A wrong field surfaces later, wherever the code first uses it.
What problem does a schema library solve that a hand-written `isUser` type guard doesn't?
With a guard, the `User` type and the checks in the guard are written separately, and nothing makes them agree; add a field to the type and the guard still compiles. A schema is a single source: the runtime check and the static type are both derived from it, so they can't drift.
When would you use `safeParse` instead of `parse`?
When invalid input is a normal outcome you want to handle, such as a form submission. `safeParse` returns `{ success: true, data }` or `{ success: false, error }`, and narrowing on `success` gives typed data in one branch and the list of issues in the other. `parse` throws, which suits data that should never be wrong, like your own config.
Where in a program should validation happen?
At the boundary, right where untrusted data enters: the response handler, the form submit, the config loader. After that, the inferred type tells the rest of the code the data was checked, so internal functions don't need to check again.
Why can a schema's input type differ from its output type?
Schemas can transform as they validate. A schema that coerces a form's string `"42"` into the number `42` accepts strings and produces numbers, so Zod offers `z.input` and `z.output` to name each side, and `z.infer` gives the output.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.