Course contentsShow
← TypeScript
Lesson 1277 of 1,79630. Type-Safe APIsFree lesson

Union Types for Multiple Response Shapes

Handling endpoints that return different structures based on status codes or query parameters.

Union Types for Multiple Response Shapes

What you'll learn: How to type API endpoints that return different data structures depending on status codes or query parameters.


Real-world APIs don't always return the same shape. Sometimes a successful response looks completely different from an error response. Or the same endpoint might return different structures based on query parameters—like returning a summary vs. full details.

The Multi-Shape Problem

When you call an endpoint, you might get:

  • Status 200: { success: true, data: User }
  • Status 404: { success: false, error: string }

If you try to type this as a single object, you'll lose type safety. You need TypeScript to understand "it's one shape or the other."

Using Union Types for Responses

Union types let you express "this response could be Shape A or Shape B":

interface SuccessResponse {
  success: true;
  data: {
    id: number;
    name: string;
  };
}

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

type ApiResponse = SuccessResponse | ErrorResponse;

Now when you receive a response, TypeScript knows it's one of these two shapes. You must narrow the type before accessing properties safely:

function handleResponse(response: ApiResponse) {
  if (response.success) {
    // TypeScript knows this is SuccessResponse
    console.log(response.data.name);
  } else {
    // TypeScript knows this is ErrorResponse
    console.log(response.error);
  }
}

Why This Works

The success property acts as a discriminant. When you check response.success === true, TypeScript eliminates the ErrorResponse possibility, letting you safely access response.data.

This pattern scales to multiple response shapes—just add more interfaces to your union.

Key Takeaway: Use union types with discriminant properties to type endpoints that return different structures based on status, parameters, or context—then narrow with type guards to safely access the correct shape.