ProgramGuru

Fetch API with TypeScript

Fetch API with TypeScript — the core idea

fetch returns a Promise<Response>. It rejects for network-level failures, but HTTP responses such as 404 still resolve and must be checked using response.ok/status. Parsing JSON returns runtime data that needs validation before trusting a TypeScript interface.

What you’ll learn

  • Explain fetch api with typescript with a concrete use case.
  • Run the example and account for every line of its output.
  • Recognize the difference between compile-time checking and runtime behavior.

Understand the rules and when to use them

Reading the code: A local data: URL supplies deterministic JSON without network access (supported by modern Node fetch). response.ok succeeds. The parsed value starts as unknown and is narrowed before reading count, which prints 3.

Keep the boundary clear: Annotating await response.json() as MyInterface is not actual validation. Validate required properties and types, especially at API boundaries.

See the idea as a flow

Fetch API with TypeScript — conceptual flowfetch URL then Response.ok then validate JSONFetch API with TypeScript1fetch URL2Response.ok3validate JSONAsynchronous operations may resume after the current JavaScript stack.
Follow the three stages and identify what happens in TypeScript versus JavaScript.

Run the complete TypeScript example

Save the code as fetch-api.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.

TypeScript code

async function main(): Promise<void> {
  const url = "data:application/json,%7B%22count%22%3A3%7D";
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  const value: unknown = await response.json();
  if (typeof value === "object" && value !== null && "count" in value && typeof value.count === "number") {
    console.log(value.count);
  }
}
main().catch(console.error);

Verified output

3

Build: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable fetch-api.ts; run: node fetch-api.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.

Trace the example line by line

A local data: URL supplies deterministic JSON without network access (supported by modern Node fetch). response.ok succeeds. The parsed value starts as unknown and is narrowed before reading count, which prints 3.

The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.

Avoid this common mistake

Annotating await response.json() as MyInterface is not actual validation. Validate required properties and types, especially at API boundaries.

Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.

Practice independently

Change the JSON to include a name:string and validate both fields. In a real HTTP call, also handle non-2xx statuses.

Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.

Check your understanding

How does fetch treat an HTTP 404 response?
Choose one answer. You can try again.

Answer and explanation

It resolves to a Response with ok false; the caller checks the HTTP status.

A local data: URL supplies deterministic JSON without network access (supported by modern Node fetch). response.ok succeeds. The parsed value starts as unknown and is narrowed before reading count, which prints 3.

What to remember

fetch returns a Promise<Response>.

Try the practice change and re-run the exact program to test your understanding.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Cancelling Operations with AbortController →