Skip to content

Type-Safe API Client

Medium ~25 min

What you'll build

A fetch wrapper that takes a URL and an expected response type T, then returns Promise<T>. TypeScript verifies that callers use the correct response shape.

Goals

  • Use generics to type API response shapes
  • Apply type assertions safely after runtime checks
  • Handle errors with typed result objects
  • Understand the boundary between compile-time and runtime types

Prerequisites

  • Generics basics
  • Interfaces
  • async/await
  • fetch API

Steps

  1. 1

    Define the response types

    Create interfaces for the API responses you expect. These types are compile-time only — they describe the shape of the data.

    Code
    interface User { id: number; name: string; email: string; }
    interface Post { id: number; title: string; body: string; }

    Expected result

    Two interfaces are defined. No runtime code yet.

  2. 2

    Write the generic fetch function

    Create a function apiFetch<T> that calls fetch, parses JSON, and asserts the result as T. The generic parameter lets callers specify the expected type.

    Code
    async function apiFetch<T>(url: string): Promise<T> {
      const res = await fetch(url);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      return (await res.json()) as T;
    }

    Expected result

    A generic function that returns Promise<T> for any URL.

  3. 3

    Use the typed client

    Call apiFetch with explicit type parameters. TypeScript now knows the shape of each response, enabling autocomplete and type checking.

    Code
    const user = await apiFetch<User>("/api/users/1");
    console.log(user.name); // type-safe access
    
    const post = await apiFetch<Post>("/api/posts/1");
    console.log(post.title); // type-safe access

    Expected result

    Autocomplete works for user.name and post.title. Typos are caught at compile time.

  4. 4

    Add type guards & runtime checks

    Write a user-defined type guard function to validate data shape at runtime, combined with the unknown type to safely handle external input. Type guards give TypeScript runtime type safety too.

    Code
    type User = { id: number; name: string };
    
    function isUser(value: unknown): value is User {
      if (typeof value !== "object" || value === null) return false;
      const obj = value as Record<string, unknown>;
      return typeof obj.id === "number" && typeof obj.name === "string";
    }
    
    // Usage with unknown input
    const data: unknown = JSON.parse(rawJson);
    if (isUser(data)) {
      console.log(data.name); // TS knows data is User here
    } else {
      console.error("Invalid user data");
    }

    Expected result

    When isUser returns true, TS narrows data to User type; invalid data goes to the else branch.

  5. 5

    Add generic utility functions

    Write generic utility functions (e.g., deepFreeze, groupBy) to enhance type-safe reuse. Generics let utility functions work with multiple types without losing type information.

    Code
    function groupBy<T, K extends string | number>(
      items: T[],
      keyFn: (item: T) => K
    ): Record<K, T[]> {
      const result = {} as Record<K, T[]>;
      for (const item of items) {
        const key = keyFn(item);
        (result[key] ??= []).push(item);
      }
      return result;
    }
    
    // Usage
    const byAge = groupBy(users, u => u.age);

    Expected result

    groupBy groups any array by key, returning a type-safe Record.

Try it yourself

What you learned

You built a generic API client where the return type is determined by the caller. This is the most common real-world use of generics — bridging untyped runtime data to typed compile-time interfaces.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic