#typescript #project #api

Day 29: Project - Type-Safe API Client

The Capstone

Welcome to Day 29! Let’s build something real using Generics, Interfaces, and Async/Await.

The Goal

Create a function request that:

  1. Wraps fetch.
  2. Is Generic (returns typed data).
  3. Handles errors.

Step 1: Define Interfaces

interface APIResponse<T> {
  data: T;
  status: number;
}

interface User {
  id: number;
  name: string;
}

Step 2: The Generic Function

async function request<T>(url: string): Promise<APIResponse<T>> {
  const response = await fetch(url);
  const json = await response.json();

  if (!response.ok) {
    throw new Error(\`Error \${response.status}\`);
  }

  return {
    data: json as T,
    status: response.status
  };
}

Step 3: Usage

async function main() {
  try {
    const response = await request<User>("https://api.example.com/user/1");
    // TypeScript knows response.data is User!
    console.log(response.data.name); 
  } catch (error) {
    console.error(error);
  }
}

Challenge for Today

  1. Implement a post method in your client.
  2. It should take a second generic BodyType.
  3. function post<ReturnType, BodyType>(url: string, body: BodyType)

See you on Day 30 for the Finale!