TypeScript · Lesson 39 of 42
Typing API data and checking it at runtime
Learn why a type annotation cannot protect you from bad data, then treat incoming data as unknown and validate it with type guards before using it.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will close the biggest gap in any TypeScript program: the boundary where data from outside, such as a server, a file or a form, enters your typed code. Inside your program, the compiler checks everything. At the boundary, it can check nothing, so you must.
The trap
Suppose a server returns a user as JSON. It is tempting to tell the compiler what to expect:
type User = { id: number; name: string; email: string };
const json = '{"id": "17", "name": "Asha"}';
const user = JSON.parse(json) as User;
console.log(user.email.toLowerCase());TypeError: Cannot read properties of undefined (reading 'toLowerCase')That compiles without complaint, and then it crashes. The data has a string id and no email, but as User told the compiler to believe otherwise. As the earlier lesson on assertions said, as is erased and checks nothing. The real data and the type you wrote were never compared. The crash also happens later and far from the cause, which makes it hard to trace.
Types describe what your code expects. They cannot know what a server sends, because types vanish when the program runs.
Treat outside data as unknown
The honest type for data you did not create is unknown. Then the compiler forces you to check it before use:
async function loadUser(): Promise<unknown> {
return JSON.parse('{"id": 17, "name": "Asha", "email": "asha@example.com"}');
}
async function main(): Promise<void> {
const data = await loadUser();
console.log(typeof data);
}
main();object(Some APIs, such as the built-in JSON.parse, return any. Assigning that to an unknown variable straight away, as above, restores safety.)
Validate with a type guard
You met type guards earlier. A guard that checks every field turns unknown into a real, trustworthy User:
type User = { id: number; name: string; email: 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" &&
typeof record.name === "string" &&
typeof record.email === "string"
);
}
const good: unknown = JSON.parse('{"id": 17, "name": "Asha", "email": "asha@example.com"}');
const bad: unknown = JSON.parse('{"id": "17", "name": "Asha"}');
console.log(isUser(good), isUser(bad));
if (isUser(good)) {
console.log(good.email.toLowerCase());
}true false
asha@example.comThe as Record<string, unknown> inside the guard is acceptable, because it is followed by checks on every property. The assertion allows the code to read fields; the typeof checks do the real work.
A parse function returns a result
A guard answers yes or no. A parse function goes further: it either returns a typed value or says what was wrong. That combines the guard with the result type from the discriminated unions lesson:
type User = { id: number; name: string };
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
function parseUser(data: unknown): Result<User> {
if (typeof data !== "object" || data === null) {
return { ok: false, error: "expected an object" };
}
const record = data as Record<string, unknown>;
if (typeof record.id !== "number") {
return { ok: false, error: "id must be a number" };
}
if (typeof record.name !== "string" || record.name === "") {
return { ok: false, error: "name must be a non-empty string" };
}
return { ok: true, value: { id: record.id, name: record.name } };
}
for (const text of ['{"id": 1, "name": "Asha"}', '{"id": "1", "name": "Asha"}', "null"]) {
const result = parseUser(JSON.parse(text));
console.log(result.ok ? `user ${result.value.name}` : `invalid: ${result.error}`);
}user Asha
invalid: id must be a number
invalid: expected an objectNotice what the function returns: a new object built from checked fields, not the original data. Extra fields the server added are dropped, and the output matches your type exactly. The error messages say which field failed, which is invaluable when an API changes unexpectedly.
Arrays and nested data
Real responses contain lists and nested objects. Validate one piece at a time and compose the checks:
type Product = { sku: string; price: number };
function isProduct(value: unknown): value is Product {
if (typeof value !== "object" || value === null) return false;
const r = value as Record<string, unknown>;
return typeof r.sku === "string" && typeof r.price === "number";
}
function isProductList(value: unknown): value is Product[] {
return Array.isArray(value) && value.every(isProduct);
}
const payload: unknown = JSON.parse('[{"sku":"A1","price":2.5},{"sku":"B2","price":4}]');
if (isProductList(payload)) {
const total = payload.reduce((sum, p) => sum + p.price, 0);
console.log(`${payload.length} products, total ${total}`);
}2 products, total 6.5Schema libraries
Hand-written validators are clear and need no dependencies, but they have a weakness: the Product type and the isProduct check are two separate things that can drift apart. Add a field to one and forget the other, and the compiler will not notice. Libraries that define a schema once, and derive both the run-time validator and the TypeScript type from it, solve that. Examples include Zod and Valibot. Check each library's documentation and choose by the needs of your project. The principle is the same as in this lesson: data from outside is unknown until a validator says otherwise.
Where the boundary is
Validate wherever data enters your program:
- network responses and incoming request bodies on a server,
JSON.parseand file contents,- form input and query strings,
localStorageand cookies,- environment variables and command-line arguments.
Inside the program, after validation, trust the types. You get the safety of validation once, at the edge, and the speed and clarity of plain typed code everywhere else.
Common mistakes
Using as User on JSON. It is not validation. Use a guard or a schema.
Validating too little. A guard that checks only that the value is an object proves nothing about its fields.
Validating everywhere. Check at the boundary once, then pass the typed value around.
Trusting your own API. Servers change, and so do versions. Validate even data from services you control.
Returning the raw data from a parse function. Return a freshly built object, so only checked fields escape.
Exercise
Write parseOrder(data: unknown): Result<Order> for an order with an id number, a customer string and an items array of { sku: string; qty: number }. Test it with valid data, a missing field, a wrong type, an item with a negative quantity and null. Make the error messages say exactly which field failed.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.