Back to Rules

A reusable interface for handling API responses in TypeScript

Code

interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
  success: boolean;
  timestamp: string;
  pagination?: {
    page: number;
    limit: number;
    total: number;
    hasMore: boolean;
  };
  meta?: Record<string, unknown>;
}

// Example usage with a User type
interface User {
  id: string;
  name: string;
  email: string;
  role: 'admin' | 'user';
}

// Using the ApiResponse with User type
type UserApiResponse = ApiResponse<User>;
typescript
Posted by Tejashwa Tiwari1/29/2024