← Back to TypeScript Course | Chapter 15: TypeScript with APIs | Lesson 1 of 6

Fetch API with Types

The Fetch API lets TypeScript applications request data from web servers. TypeScript can describe request data and API responses so that your asynchronous code is safer and easier to understand.

Basic Typed Fetch

A basic typed fetch call still returns Promise<Response> from the native fetch API — the actual data typing has to happen after calling .json(), since fetch itself has no idea what shape the response body will be.

Example: Basic Typed Fetch

typescript
interface User {
  id: number;
  name: string;
}
async function getUser(): Promise<User> {
  const response = await fetch("data.php");
  return response.json();
}
getUser().then(console.log);

Checking HTTP Responses

Checking response.ok before parsing the body is essential because a typed fetch call succeeds (resolves) even for HTTP error statuses like 404 — fetch only rejects on network failures, never on HTTP error codes themselves.

Example: Checking HTTP Responses

typescript
async function getUser() {
  const response = await fetch("data.php");
  if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`);
  }
  return response.json();
}
getUser().then(console.log).catch(console.error);

POST Requests with Types

A typed POST request sets the request body with JSON.stringify on a typed payload object and typically annotates the response the same way as a GET, since fetch itself doesn't distinguish request types in its typing.

Example: POST Requests with Types

typescript
interface NewUser {
  name: string;
}
async function createUser(payload: NewUser) {
  const response = await fetch("data.php", {
    method: "POST",
    body: JSON.stringify(payload),
  });
  return response.json();
}
createUser({ name: "Ravi" }).then(console.log);

Typed Arrays from Fetch

Typing arrays from fetch means asserting or validating that the parsed JSON is actually an array of the expected item type, since .json()'s return type is any and won't catch a mismatched shape on its own.

Example: Typed Arrays from Fetch

typescript
interface Item {
  id: number;
}
async function getItems(): Promise<Item[]> {
  const response = await fetch("data.php");
  const data = await response.json();
  if (!Array.isArray(data)) throw new Error("Expected an array");
  return data;
}
getItems().then(console.log);

Reusable Fetch Helper

A reusable fetch helper wraps the fetch-then-.json()-then-validate pattern into one generic function, so callers get a typed result without re-writing response-checking boilerplate at every call site.

Example: Reusable Fetch Helper

typescript
async function fetchJson<T>(url: string): Promise<T> {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}
interface User { name: string; }
fetchJson<User>("data.php").then((user) => console.log(user.name));
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.