Sub topic 12
Validating Data at Async Boundaries
Assume you know basic TypeScript types, unions, narrowing, generics, and JavaScript Promise and async/await syntax. This chapter focuses on a boundary: a point where data enters your program from code that TypeScript cannot inspect, such as an HTTP response.
Why asynchronous data is untrusted
TypeScript checks your source code before it runs. It does not check the JSON returned by a server. The server might return an old shape, an error object, missing fields, or values with the wrong types.
Response.json() parses text into a JavaScript value. The value can be any valid JSON:
- An object
- An array
- A string or number
null- An object with unexpected fields
A type assertion only changes the compiler's belief:
const user = (await response.json()) as User;This does not inspect the value. If name is missing, the program can still fail later.
Validation checks the value at runtime and narrows its type for TypeScript.
Write a type guard
A type guard is a function whose return type tells TypeScript that a condition has established a type. Its return type uses the form value is Type.
type User = {
id: number;
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 === "number" &&
Number.isInteger(record.id) &&
typeof record.name === "string"
);
}
async function fetchUser(url: string): Promise<User> {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed with HTTP ${response.status}`);
}
const raw: unknown = await response.json();
if (!isUser(raw)) {
throw new Error("Response was not a valid User");
}
return raw;
}The assertion inside isUser is limited to inspecting an object as a key-value record. The function does not claim that the object is a User until every required property has been checked.
After if (!isUser(raw)), TypeScript narrows raw from unknown to User. The caller receives Promise<User> only when validation succeeds.
Choose validation depth deliberately
A validator should check the fields your code depends on. It does not always need to reject every extra field. Many APIs add fields over time, so accepting unknown properties can make clients more compatible.
| Data shape | Useful validation |
|---|---|
| User object | Check object status, required fields, and primitive types |
| Array of users | Check `Array.isArray` and validate every element |
| Paginated response | Validate the page object, item array, and pagination fields |
| Untrusted identifier | Check its type, range, and allowed format |
For larger schemas, a validation library can generate validators from schemas and produce better error details. The principle stays the same: parse first, validate second, use the narrowed value third.
Validate more than HTTP responses
The same boundary exists when data comes from local storage, a Web Worker message, a database driver, a plugin, or a command-line argument. TypeScript cannot verify those values at runtime.
Validation also protects code when the server returns a valid JSON error with an unexpected shape. Check response.ok before parsing the success type, and decide whether error responses need their own validator.
Do not use any to bypass the boundary. If a generic helper returns parsed data, make validation part of its API:
async function fetchValidated<T>(
url: string,
isT: (value: unknown) => value is T
): Promise<T> {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const raw: unknown = await response.json();
if (!isT(raw)) {
throw new Error(`Invalid response from ${url}`);
}
return raw;
}The generic type T is safe here because the caller supplies the runtime check that proves T.
Exercise
Why is const user = (await response.json()) as User insufficient at an API boundary?
Show answer
The assertion changes only the compile-time type. It does not inspect the runtime value, so malformed or unexpected JSON can still be treated as a User.