typescript

Generic API Response Type

Type-safe API response wrapper for consistent error handling

Tarun Sharma
Tarun SharmaJanuary 15, 2024 ยท 1 min read ยท Last Updated:
type ApiResponse<T> = { success: true; data: T } | { success: false; error: string };

async function fetchApi<T>(url: string): Promise<ApiResponse<T>> {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      return { success: false, error: `HTTP ${response.status}` };
    }
    const data: T = await response.json();
    return { success: true, data };
  } catch (error) {
    return { success: false, error: (error as Error).message };
  }
}

Usage

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

const result = await fetchApi<User>('/api/user/1');

if (result.success) {
  console.log(result.data.name); // Type-safe access
} else {
  console.error(result.error);
}

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Tarun Sharma

Written byTarun Sharma
Full-stack developer and tech educator with 10+ years of experience building scalable applications. Passionate about Node.js, NestJS, React, and cloud technologies. Creator of 50+ courses on Udemy and active YouTube educator helping developers level up their skills.
Connect

Is this page helpful?

Related VideosView All

Stack Overflow Clone - APIs Integration Redux Toolkit [Closure] - App Demo #05

Become Ninja Developer - API security Best Practices with Node JS Packages #15

Nest JS Microservices using HTTP Gateway and Redis Services (DEMO) #nestjs #microservices #16