Error Response Types
What you'll learn: How to model both success and error API responses as discriminated unions, ensuring type-safe handling of different HTTP status outcomes.
When calling an API, you'll receive different response shapes depending on whether the request succeeded or failed. A 200 OK might return user data, while a 404 Not Found returns an error message. Without proper typing, you're forced to check these at runtime without compiler help.
The Problem: One Type Doesn't Fit All
Consider a user profile endpoint. Success gives you { id, name, email }, but errors return { error: string, statusCode: number }. If you type the response as just the success case, you'll get runtime crashes when errors occur.
Discriminated Unions for HTTP Outcomes
The solution is modeling both possibilities as a discriminated union:
type SuccessResponse = {
status: 'success';
data: { id: number; name: string; email: string };
};
type ErrorResponse = {
status: 'error';
message: string;
statusCode: number;
};
type ApiResponse = SuccessResponse | ErrorResponse;
The status property acts as the discriminant, letting TypeScript narrow the type:
function handleResponse(response: ApiResponse) {
if (response.status === 'success') {
console.log(response.data.name); // ✓ TypeScript knows data exists
} else {
console.error(response.message); // ✓ TypeScript knows message exists
}
}
Multiple Error Types
You can model different HTTP statuses separately:
type ValidationError = {
status: 'validation_error';
errors: Record<string, string>;
};
type NotFoundError = {
status: 'not_found';
resource: string;
};
type ApiResponse = SuccessResponse | ValidationError | NotFoundError;
Now your error handling becomes exhaustive and type-safe.
Key Takeaway: Model API responses as discriminated unions with separate types for success and different error cases, using a status field as the discriminant for compile-time safety across all HTTP outcomes.