Middle
How would you type the backend responses in TypeScript if one endpoint can return different structures: a paginated list, an error, or an empty result? How to organize types to make it convenient to use throughout the project?
sobes.tech AI
Answer from AI
For typing backend responses that can return different structures (for example, a paginated list, an error, or an empty result), it is convenient to use union types and interfaces in TypeScript.
Example of organizing types:
interface Pagination {
page: number;
pageSize: number;
total: number;
}
interface Item {
id: string;
name: string;
// other fields
}
interface SuccessResponse {
data: Item[];
pagination: Pagination;
}
interface EmptyResponse {
data: [];
pagination: Pagination;
}
interface ErrorResponse {
error: string;
code: number;
}
// Unified response type
type ApiResponse = SuccessResponse | EmptyResponse | ErrorResponse;
// Example of handling response function
function handleResponse(response: ApiResponse) {
if ('error' in response) {
console.error('Error:', response.error);
} else if (response.data.length === 0) {
console.log('Empty result');
} else {
console.log('Data:', response.data);
}
}
This approach allows:
- Clearly describing each possible response structure.
- Using key presence checks (e.g.,
error) to determine the response type. - Conveniently using types throughout the project by importing them from a single types file.
If there are many responses and they are complex, you can additionally use generics and utility types for reusing common parts of types.