Back to library
🔷TypeScripttypescriptintermediate

Generic API Response Type

Reusable type for API responses with success and error states

typesapigenerics

Code

1// Generic API response type
2type ApiResponse<T> = {
3  success: true;
4  data: T;
5} | {
6  success: false;
7  error: {
8    message: string;
9    code?: string;
10  };
11};
12
13// Helper function to create success response
14function success<T>(data: T): ApiResponse<T> {
15  return { success: true, data };
16}
17
18// Helper function to create error response
19function error<T>(message: string, code?: string): ApiResponse<T> {
20  return { success: false, error: { message, code } };
21}
22
23// Usage example
24interface User {
25  id: string;
26  name: string;
27  email: string;
28}
29
30async function fetchUser(id: string): Promise<ApiResponse<User>> {
31  try {
32    const response = await fetch(`/api/users/${id}`);
33    
34    if (!response.ok) {
35      return error('Failed to fetch user', 'FETCH_ERROR');
36    }
37    
38    const user = await response.json();
39    return success(user);
40  } catch (err) {
41    return error('Network error', 'NETWORK_ERROR');
42  }
43}
44
45// Type-safe usage
46const result = await fetchUser('123');
47
48if (result.success) {
49  console.log(result.data.name); // TypeScript knows data exists
50} else {
51  console.error(result.error.message); // TypeScript knows error exists
52}

Quick Tips

  • Click the "Copy" button to copy the code to your clipboard
  • This code is production-ready and can be used in your projects
  • Check out related snippets below for more examples

Related Snippets

Build Your Own Snippet Library

Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.