Back to Snippets
Generic API Response Type
typescript
TypeScript
A reusable TypeScript type for API responses with proper error handling.
Code
1interface ApiResponse<T> {
2data: T | null;
3error: string | null;
4status: "success" | "error" | "loading";
5}
6
7interface User {
8id: string;
9name: string;
10email: string;
11}
12
13async function fetchUser(id: string): Promise<ApiResponse<User>> {
14try {
15const response = await fetch(`/api/users/${id}`);
16const data = await response.json();
17return { data, error: null, status: "success" };
18} catch (error) {
19return {
20data: null,
21error: error instanceof Error ? error.message : "Unknown error",
22status: "error"
23};
24}
25}Details
Language
typescript
Category
TypeScript