Sobes.tech
Middle

How exactly to type a list with pagination? How to use type intersection for different answer options?

sobes.tech AI

Answer from AI

To type a paginated list in TypeScript, it is common to create an interface that describes the structure of the response with data and pagination metadata:

interface PaginatedResponse<T> {
  items: T[];
  totalCount: number;
  page: number;
  pageSize: number;
}

// Example usage:
interface User {
  id: number;
  name: string;
}

const response: PaginatedResponse<User> = {
  items: [{ id: 1, name: 'Alice' }],
  totalCount: 100,
  page: 1,
  pageSize: 10,
};

For different response variants with type intersections, the & operator can be used to combine properties of multiple types:

interface SuccessResponse {
  success: true;
  data: User[];
}

interface ErrorResponse {
  success: false;
  error: string;
}

// Intersection for the success response with pagination
type PaginatedSuccessResponse = PaginatedResponse<User> & SuccessResponse;

// Usage
const result: PaginatedSuccessResponse = {
  items: [{ id: 1, name: 'Alice' }],
  totalCount: 50,
  page: 2,
  pageSize: 10,
  success: true,
  data: [{ id: 1, name: 'Alice' }],
};

Thus, type intersections allow combining different parts of responses, ensuring strict typing and ease of working with various API response options.

How exactly to type a list with pagination? How to… - sobes.tech