Sub topic 12
Validating data at async boundaries
This chapter assumes you know basic TypeScript types, generics at the level of Array<T>, async/await, and union narrowing. You should also have read the earlier chapters on Promise<T>, Awaited<T>, and error handling with unknown.
Where the type system stops
TypeScript checks your program at compile time. Types are erased before the code runs. When data arrives from outside your program, such as an HTTP response, a file, a message queue, or localStorage, the compiler has no way to know what it contains. The data crosses a boundary from a world you control to one you do not.
Async code is where most of these boundaries sit. Each await fetch(...) or await readFile(...) brings in a value whose shape is a promise from someone else. If you write a type for that value, the compiler believes you. It does not check.
Here is the helper from the earlier code example:
async function fetchJson<T>(url: string, signal?: AbortSignal): Promise<T> {
const res = await fetch(url, { signal });
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
return (await res.json()) as T;
}The last line is a type assertion. The expression x as T tells the compiler to treat x as T. It does not convert or check anything. res.json() returns Promise<any>, and any is assignable to every type, so the assertion compiles whatever the server sends.
Why assertions fail in practice
Suppose a caller writes this:
interface User {
id: number;
name: string;
}
async function showUser(id: number): Promise<void> {
const user = await fetchJson<User>(`/api/users/${id}`);
console.log(user.name.toUpperCase());
}This compiles. It also crashes at runtime in several realistic cases:
- The API renames
nametodisplayName.user.nameisundefined, andtoUpperCasethrows aTypeError. - The API returns
{ "id": "42" }with a string id. Later arithmetic onidproduces wrong results without any error. - A proxy returns an error body such as
{ "error": "rate limited" }with status 200. - The API returns
nullfor a missing user.
The failure appears far from its cause. The stack trace points at toUpperCase, not at the network boundary where the bad data entered. The type User made the code look safe while checking nothing.
Treat boundary data as `unknown`
The honest type for parsed external data is unknown. It accepts any value, but you cannot use it until you narrow it. This moves the burden of proof to the place where the data enters.
async function fetchUnknown(url: string, signal?: AbortSignal): Promise<unknown> {
const res = await fetch(url, { signal });
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
const body: unknown = await res.json();
return body;
}The annotation const body: unknown is allowed because any is assignable to unknown. From here on the compiler stops you from reading properties until you prove what the value is.
Validate by hand with a type guard
A type guard is a function whose return type is a type predicate such as value is User. When it returns true, the compiler narrows the argument to that type in the calling code.
interface User {
id: number;
name: string;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isUser(value: unknown): value is User {
return (
isRecord(value) &&
typeof value.id === "number" &&
typeof value.name === "string"
);
}
async function loadUser(id: number): Promise<User> {
const body = await fetchUnknown(`/api/users/${id}`);
if (!isUser(body)) {
throw new Error("Response is not a valid User");
}
return body;
}Now a bad response fails at the boundary, with a message that names the problem. The rest of the program can trust User.
Hand-written guards have a drawback: nothing links the guard to the interface. If you add email: string to User and forget to update isUser, the guard keeps returning true for objects that lack an email. The compiler cannot catch this, because a type predicate is also an unchecked claim. You have moved the assertion into a smaller, easier-to-audit place, but it is still there.
Validate with a schema and derive the type
A schema library fixes the drift problem by defining the shape once and deriving the static type from it. Zod, Valibot, and ArkType all work this way. The example below uses Zod.
import { z } from "zod";
const UserSchema = z.object({
id: z.number(),
name: z.string(),
});
type User = z.infer<typeof UserSchema>;
// User is { id: number; name: string }
async function loadUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
const body: unknown = await res.json();
return UserSchema.parse(body);
}UserSchema.parse returns a value typed as User and throws a ZodError if the data does not match. The runtime check and the compile-time type come from one definition, so they cannot disagree. Add a field to the schema and the type changes with it.
If you prefer not to throw, safeParse returns a discriminated union:
import { z } from "zod";
const UserSchema = z.object({
id: z.number(),
name: z.string(),
});
type User = z.infer<typeof UserSchema>;
async function tryLoadUser(id: number): Promise<User | null> {
const res = await fetch(`/api/users/${id}`);
const body: unknown = await res.json();
const parsed = UserSchema.safeParse(body);
if (!parsed.success) {
console.error(parsed.error.issues);
return null;
}
return parsed.data;
}This is the same idea as the Result union from the earlier chapter. The success field discriminates the two cases, and data exists only after you check it.
A reusable validated fetch
You can make the generic helper honest by requiring a validator. The caller supplies the proof, and the type parameter is inferred from it instead of being asserted.
import { z } from "zod";
async function fetchValidated<S extends z.ZodTypeAny>(
url: string,
schema: S,
signal?: AbortSignal,
): Promise<z.infer<S>> {
const res = await fetch(url, { signal });
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
const body: unknown = await res.json();
return schema.parse(body);
}
const PostsSchema = z.array(z.object({ id: z.number(), title: z.string() }));
async function main(): Promise<void> {
const posts = await fetchValidated("/api/posts", PostsSchema);
console.log(posts[0]?.title);
}Compare this with fetchJson<T>. There the caller chose T freely. Here T is determined by the schema, so the return type always matches what was checked. The AbortSignal parameter keeps the cancellation support from the earlier chapter.
If you do not want a library dependency, a validator can be any function from unknown to T:
type Parser<T> = (input: unknown) => T;
async function fetchWith<T>(url: string, parse: Parser<T>): Promise<T> {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
return parse(await res.json());
}This keeps the same property: the type comes from the parser, not from a cast.
Edge cases to plan for
- Extra fields. Most schema libraries strip or ignore unknown keys by default. Check the library's setting if you need to reject them or keep them.
- Numbers and dates. JSON has no date type. A date arrives as a string, so the schema must either keep it as a string or parse it into a
Date. The static type of the output then differs from the type of the input. - Nullable and optional fields.
nulland a missing key are different values. Decide which the API uses and model it exactly. A server that sendsnullfor "no value" needsz.string().nullable(), not.optional(). - Large numbers.
JSON.parseturns numbers beyond 2^53 into imprecise doubles. If ids can be that large, ask the API to send them as strings. - Failures are data too. The error body from a 4xx response has its own shape. Validate it with a separate schema instead of assuming it matches the success shape.
- Cost. Validation walks the whole value. For large payloads on hot paths, measure before deciding how much to check.
What validation does and does not cover
Validation protects you from wrong data at the point of entry. It does not remove other async risks. A validated response can still be stale, arrive out of order, or come after the caller has moved on. Those problems belong to cancellation, ordering, and error handling, covered in other chapters.
Validate where data enters, then pass the typed result inward. Re-validating at every function would waste work, and skipping validation at the edge would leave the type as an unchecked claim.
Choosing an approach
| Approach | Checked at runtime | Type stays in sync | Cost |
|---|---|---|---|
| `res.json() as T` | No | No | None, but unsafe |
| Hand-written type guard | Yes | No, you maintain both | Your own code |
| Schema library, `z.infer` | Yes | Yes, one definition | A dependency and some runtime work |
| Generated client from an API spec | Depends on the generator | Yes, if regenerated | Build step |
For internal data that your own code just wrote, such as a value you serialized a moment ago, an assertion can be reasonable. For anything that crosses a network, a file, or a user's browser storage, validate.
Exercise
A teammate writes const cfg = (await res.json()) as Config; and says it is safe because Config is an interface with every field typed. What is wrong with this reasoning, and what change would make the code check its input?
Show answer
The assertion is not a check. res.json() returns any, and as Config tells the compiler to trust the shape without testing it, so a response with missing or wrongly typed fields still compiles and fails later, far from the cause. Annotate the parsed value as unknown and validate it before use, either with a type guard or with a schema such as ConfigSchema.parse(body), where Config is derived with z.infer<typeof ConfigSchema> so the type and the check cannot drift apart.
Exercise
Why is fetchValidated(url, schema) safer than fetchJson<T>(url), even though both return Promise of some type?
Show answer
In fetchJson<T> the caller picks T and nothing connects it to the response, so the type is an unchecked claim. In fetchValidated the return type is z.infer<S>, computed from the schema that actually ran against the data, so the compile-time type always matches what was verified at runtime.
Exercise
An API sometimes returns { "name": null } for users without a name. Which Zod definition models the field correctly: z.string().optional() or z.string().nullable(), and why?
Show answer
z.string().nullable(). The key is present with the value null, and optional() only allows the value undefined or a missing key. Using optional() would make validation reject the response.