×

typescript · level 3 · unit 7 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Wrap fetch once, and every request becomes safe.

Real apps ask servers for data. Gwecode answers requests to https://api.example.com with a practice server, so you can try this safely. Each address you can ask for is an . Replies can be missing, broken or the wrong shape, and json() gives any, which trusts everything.

A is a small function around another one that adds safety. getJson takes a URL and a type guard, checks the status and the data, and hands back a Result<T>. Every caller gets typed data or a clear error, never a surprise.

type Result<T> = { ok: true; value: T } | { ok: false; error: string };
async function getJson<T>(url: string, guard: (data: unknown) => data is T): Promise<Result<T>> {
  const reply = await fetch(url);
  if (!reply.ok) {
    return { ok: false, error: `Server said ${reply.status}` };
  }
  const data: unknown = await reply.json();
  if (!guard(data)) {
    return { ok: false, error: "Unexpected data" };
  }
  return { ok: true, value: data };
}
const isText = (data: unknown): data is string => typeof data === "string";
getJson("https://api.example.com/motto", isText).then((result) => console.log(result));

.then takes a callback and runs it once the promise has its value.