Skip to article content
FrontendXLesson 34 / 40

A typed API client

Go from the first annotated variable to writing your own conditional, mapped and infer-based utility types, while keeping a clear line between compile-time checking and runtime behavior.

advanced · about 50 minutes · 3 exercises

  • Predict
  • Implement
  • Debug

What you will be able to do

#
  • Type request and response shapes.
  • Validate untrusted responses at the boundary.
  • Return typed errors instead of any.

Overview

#

Define the contract

snippet.ts
type User = { id: string; name: string };

A typed client

snippet.ts
async function getUser(id: string): Promise<User> {
  const res = await fetch(`/api/users/${id}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return (await res.json()) as User;
}

The as User is an assertion: res.json() returns any. It is a claim, not a check.

Validating the boundary

snippet.ts
function isUser(value: unknown): value is User {
  return typeof value === "object" && value !== null &&
    typeof (value as User).id === "string" && typeof (value as User).name === "string";
}

Call isUser after parsing and throw or return a Result when it fails.

Generic request helper

snippet.ts
async function request<T>(url: string, parse: (value: unknown) => T): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return parse(await res.json());
}

Passing the parser keeps the type honest: the caller proves the shape.

Errors as data

Returning a Result makes HTTP failures explicit and avoids throwing across layers.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Implement

    Implement `request<T>(url: string, parse: (value: unknown) => T): Promise<T>` that throws on a non-ok response.

    starter.typescript
    export async function request<T>(url: string, parse: (value: unknown) => T): Promise<T> {
      // your code
    }
    

    Reveal the reference answer
    reference.typescript
    export async function request<T>(url: string, parse: (value: unknown) => T): Promise<T> {
      const res = await fetch(url);
      if (!res.ok) throw new Error("HTTP " + res.status);
      return parse(await res.json());
    }
    

    Authored expected output: Compiles with no errors. Runtime: a 200 response returns parse(json); a 500 throws.

    The parser parameter proves the shape instead of asserting it.

  2. Exercise 2Predict

    Does `fetch` reject when the server returns HTTP 500?

    Choose the best answer
  3. Exercise 3Debug

    This client trusts an untyped response. Add a guard so the type is real. ```ts async function getUser(id: string): Promise<User> { return (await fetch(`/api/users/${id}`)).json() as User; } ```

    starter.typescript
    async function getUser(id: string): Promise<User> {
      return (await fetch(`/api/users/${id}`)).json() as User;
    }
    

    Reveal the reference answer
    reference.typescript
    async function getUser(id: string): Promise<User> {
      const res = await fetch("/api/users/" + id);
      if (!res.ok) throw new Error("HTTP " + res.status);
      const data: unknown = await res.json();
      if (!isUser(data)) throw new Error("invalid user payload");
      return data;
    }
    
    function isUser(value: unknown): value is User {
      return (
        typeof value === "object" &&
        value !== null &&
        typeof (value as User).id === "string" &&
        typeof (value as User).name === "string"
      );
    }
    

    Authored expected output: Compile-time unchanged; runtime now rejects a malformed body instead of returning it as User.

    A guard turns the assertion into a real runtime check.

Common misconceptions

#
  • res.json() returns the declared type.
  • as User validates the response.
  • fetch rejects on HTTP 500.

Follow-up practice

#
  • typescript-type-level-challenges

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.