Skip to main content
Version: v10.5.1

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.

What you'll learn
  1. Why response.json() is untyped and what a cast really does.
  2. How to declare the response type of a request.
  3. How to type the error next to it.
  4. 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:

plain-fetch.ts
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/users has to repeat User[], and they drift apart.
  • Errors have no type. A 404 body is still parsed as User[].
  • Nothing checks at runtime. If the backend renames name to fullName, the cast still passes and user.name is undefined in 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.

src/api/users.ts
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 responseType option ("text", "blob", "arrayBuffer") returns other shapes, so a file download is typed as { response: Blob } with options: { responseType: "blob" }. See the adapter docs for the full table.
  • GraphQL adapter: a typed document (TypedDocumentNode from graphql-codegen, or gql.tada) passed as endpoint fills 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:

src/api/users.ts
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:

src/user-table.ts
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.


Congratulations!

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 response type 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.

Request extractors
Read every part of a request's type.
Validation
Check responses at runtime with Zod.