1. Concept library
  2. JavaScript & TypeScript
  3. Module 6: Async patterns and fetch

Concept

Typed fetch responses

fetch returns untyped JSON, so the type of what comes back is a promise you make to the compiler. A thin wrapper that checks the status and validates the body keeps that promise honest.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain why the type of a fetch result is a promise you make, not a fact
  2. Write a fetch wrapper that checks the status and validates the body
  3. Spot the res.json() as User cast that hides a changed API

In practice

A few lines that show Typed fetch responses doing its job.

TypeScript
async function getJson<T>(url: string, check: (v: unknown) => v is T): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) throw new Error("HTTP " + res.status + " for " + url);
  const body: unknown = await res.json();
  if (!check(body)) throw new Error("Unexpected response shape from " + url);
  return body;
}

const isUser = (v: unknown): v is User =>
  typeof v === "object" && v !== null && "id" in v && "name" in v;

The common mistake

Watch for

Writing await res.json() as User and moving on. The cast is invisible at runtime, so a changed API returns the wrong shape and the error surfaces far away as "cannot read property of undefined".

What to know first

Your roadmap puts these before Typed fetch responses, unless you already know them.

How it stays learned

Once a session shows you understand Typed fetch responses, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled
Previous in the module← Promise.all and rejection