TypeScript checks your code, not your data. When a response comes back from fetch, the compiler has no idea what's inside, and the standard library types say so: response.json() returns Promise<any>. How you handle that any decides whether a backend change shows up as a clear error at the boundary or as Cannot read properties of undefined somewhere in the UI.
The problem with casting
The common first version looks like this:
type User = { id: number; name: string; email: string };
async function getUser(id: number) {
const response = await fetch(`/api/users/${id}`);
return (await response.json()) as User;
}
as User compiles, autocompletes and looks safe. It isn't: it's an assertion, so if the API returns { "id": "7", "fullName": "Ada" } or an error object, TypeScript still treats it as a User. The same is true of generic helpers like fetchJson<User>(url) and of typing the variable directly (const user: User = await response.json(), which works because any is assignable to everything).
Step 1: treat the data as unknown
unknown is the honest type for parsed JSON. Unlike any, it doesn't let you access properties until you've checked them:
async function getJson(url: string): Promise<unknown> {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`);
return response.json();
}
Now the compiler forces the next step: proving the data has the shape you need.
Step 2: get the type from a real response
Writing interfaces by hand for a large nested response is slow and error-prone. Start from a sample instead. Given this response:
{
"id": 7,
"name": "Ada",
"address": { "city": "London", "zip": null },
"tags": ["admin"]
}
a generator such as the JSON to TypeScript converter produces:
interface Address {
city: string;
zip: null;
}
interface User {
id: number;
name: string;
address: Address;
tags: string[];
}
Review the result before you rely on it. A sample only shows the values it happens to contain: zip is typed null because it was null here, but the real type is probably string | null. Fields that are sometimes missing need ?. The guide on optional fields and null explains how to feed the generator samples that reveal them.
Step 3: check the data at runtime
Option A: a type guard
For a small type, a hand-written type predicate needs no dependencies:
function isUser(value: unknown): value is User {
if (typeof value !== "object" || value === null) return false;
const v = value as Record<string, unknown>;
return typeof v.id === "number" && typeof v.name === "string" && Array.isArray(v.tags);
}
const data = await getJson("/api/users/7");
if (!isUser(data)) throw new Error("Unexpected user response");
data.name; // string
The downside is maintenance: the guard and the type are separate, and nothing stops them from drifting apart.
Option B: a schema with Zod
A schema library defines the shape once and gives you both the runtime check and the type:
import { z } from "zod";
const User = z.object({
id: z.number(),
name: z.string(),
address: z.object({ city: z.string(), zip: z.string().nullable() }),
tags: z.array(z.string()),
});
type User = z.infer<typeof User>;
async function getUser(id: number): Promise<User> {
return User.parse(await getJson(`/api/users/${id}`));
}
parse throws a ZodError that lists every mismatch with its path, for example a number where address.zip should be a string. Use safeParse when you'd rather handle the failure without an exception:
const result = User.safeParse(await getJson(url));
if (!result.success) {
console.error(result.error.issues);
return null;
}
return result.data;
Other libraries such as Valibot, ArkType or io-ts follow the same idea. If your team already uses JSON Schema, Ajv validates against the schema, and tools such as json-schema-to-typescript generate matching types from it.
A reusable typed fetch helper
Combine the pieces into one function so every call site gets the same checks:
import type { ZodType } from "zod";
export async function fetchJson<T>(url: string, schema: ZodType<T>, init?: RequestInit): Promise<T> {
const response = await fetch(url, init);
if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`);
const type = response.headers.get("content-type") ?? "";
if (!type.includes("application/json")) throw new Error(`Expected JSON from ${url}, got ${type || "no content type"}`);
return schema.parse(await response.json());
}
const user = await fetchJson("/api/users/7", User);
The generic is now inferred from the schema, so it can't disagree with the runtime check.
How strict should the schema be?
- Unknown keys: Zod's
z.objectignores extra fields and strips them from the output by default, so the API can add fields without breaking clients. Use.strict()only when unexpected keys indicate a real problem. - Optional versus nullable:
.optional()allows the key to be missing;.nullable()allowsnull. APIs often need both for the same field. - Dates: JSON has no date type, so timestamps arrive as strings. Validate the format with
z.iso.datetime()(z.string().datetime()in Zod 3) or convert withz.coerce.date()if you wantDateobjects. - Large IDs: numbers above 2^53 lose precision in
JSON.parsebefore any schema runs. Have the API send them as strings and type them asstring.
Where to validate
Validate once, at the edge where data enters your application: the API client, a server action, a message consumer. After that, the rest of the code can trust the types. Validating again deep inside components adds noise without adding safety.
If a response fails validation and you need to see exactly what changed between the expected and the actual payload, comparing the two JSON objects pinpoints the differing paths.