Middle
There are two endpoints: getting a list of users and getting a user by ID. How do you organize response typing and work with these APIs?
sobes.tech AI
Answer from AI
For typing responses from two endpoints — the user list and user by ID — it is convenient to define separate data types that reflect the response structure.
For example, using TypeScript:
// Type for a single user
interface User {
id: string;
name: string;
email: string;
// other fields
}
// Response with a single user
interface UserResponse {
user: User;
}
// Response with a list of users
interface UsersListResponse {
users: User[];
totalCount: number; // if needed
}
To work with the API, you can create functions that return promises with typed data:
async function fetchUserById(id: string): Promise<UserResponse> {
const response = await fetch(`/api/users/${id}`);
return response.json();
}
async function fetchUsersList(): Promise<UsersListResponse> {
const response = await fetch('/api/users');
return response.json();
}
This approach allows strict control over data structure, autocompletion, and type checking in IDEs, which reduces errors and makes code maintenance easier.