Typing API responses in TypeScript
A typed response lets the compiler catch a typo, a renamed field or a forgotten null check before your users do. This
guide shows why the usual fetch approach is weaker than it looks, and how HyperFetch attaches a response type to each
request so every caller gets it.
- Why
response.json()is untyped and what a cast really does. - How to declare the response type of a request.
- How to type the error next to it.
- How to reuse the type and check it at runtime.
Why fetch responses are untyped
response.json() returns Promise<any>. Whatever you do next is a promise you make to the compiler, not something it
checks:
type User = { id: number; name: string };
// A cast: TypeScript believes you, nothing is checked
const users = (await fetch("/api/users").then((r) => r.json())) as User[];
// A generic wrapper: nicer to call, but still a cast inside
async function getJson<T>(url: string): Promise<T> {
const response = await fetch(url);
return response.json() as Promise<T>;
}
Both are fine as long as the API sends what you expect. The gaps are:
- The type lives at the call site. Every place that calls
/api/usershas to repeatUser[], and they drift apart. - Errors have no type. A
404body is still parsed asUser[]. - Nothing checks at runtime. If the backend renames
nametofullName, the cast still passes anduser.nameisundefinedin production.
The fix for the first two is to declare the type once, next to the endpoint. The fix for the third is runtime validation, covered at the end.
Declare the response type
Pass the type to the response generic. It is declared once, next to the endpoint, and every caller gets it.
type User = { id: number; name: string; email: string };
export const getUsers = client.createRequest<{ response: User[] }>()({
endpoint: "/users",
});
const { data } = await getUsers.send();
// data: User[] | null
if (data) {
data.forEach((user) => console.log(user.name));
}
data is null until a request succeeds, so TypeScript makes you handle that case. The same type flows into
useFetch(getUsers).data in React and into the cache, without repeating it.
The response generic only types data. How the body is read is up to the adapter:
- HTTP adapter: parses JSON by default. Its
responseTypeoption ("text","blob","arrayBuffer") returns other shapes, so a file download is typed as{ response: Blob }withoptions: { responseType: "blob" }. See the adapter docs for the full table. - GraphQL adapter: a typed document (
TypedDocumentNodefrom graphql-codegen, or gql.tada) passed asendpointfills the response and payload types without generics.
Typing errors next to the response
The response type has a partner: the error type. Declare it on the request for endpoint-specific errors, or on the
client for the shape every endpoint returns. error is then typed instead of unknown:
type ValidationError = { message: string; fields: Record<string, string> };
const createUser = client.createRequest<{
response: User;
payload: { name: string; email: string };
error: ValidationError;
}>()({
endpoint: "/users",
method: "POST",
});
See local error types and global error types for both sides.
Reusing the response type
You rarely need to export ResponseType by hand. The request already carries it, and ExtractResponseType reads it
back:
import type { ExtractResponseType } from "@hyper-fetch/core";
type Users = ExtractResponseType<typeof getUsers>; // User[]
export const renderUserTable = (users: Users) =>
users.map((user) => `${user.name} <${user.email}>`).join("\n");
The other extractors (payload, params, query params, error) work the same way. See request extractors.
Checking the type at runtime
Types disappear when the code is compiled. If you can't trust the API, or it's a third-party one, validate the response
with a schema library and derive the type from the schema, so the two can't drift. HyperFetch runs the check in
setResponseMapper, and a failed parse ends up in error. The full example with Zod is in the
validation guide.
You've learned how to type API responses in TypeScript with HyperFetch.
- You can tell a cast on
response.json(), a promise to the compiler, from a check. - You can define a
responsetype for any request to get strongly-typed data. - You can type the error next to it and reuse both with extractors.
- You know when to add runtime validation on top of the types.
Runnable examples: Basic data fetching and Response mapping.