Exercise: Model Structured API States with Discriminated Unions
Master discriminated unions by modeling a real-world API response with full exhaustiveness and type safety.
We'll cover the following...
We’ve seen how discriminated unions give us precision. Now let’s take that precision and put it to work.
The problem
We’re building a frontend that calls an API to fetch user profile data. The server doesn’t just return raw values—it sends structured responses that reflect the state of the request. This is a perfect use case for discriminated unions.
In this exercise, you’ll model those responses using a type-safe discriminated union.
The API can return one of three structured outcomes:
A success response that includes:
A
statusfield with the literal value"success".A
userobject with:id(number).name(string).email(string).
A failure response that includes:
A
statusfield with the literal value"failure".A
messagestring explaining what went wrong.
A pending response that includes:
A
statusfield with the literal value"pending".A
retryAftertimestamp in milliseconds (number).
Your tasks:
Define a discriminated union type called
ProfileApiResponsethat captures all three cases above.Write a function
handleApiResponse(response: ProfileApiResponse): stringthat returns a human-readable message depending on the response type.Use a
switchon the discriminant (status) to narrow the type.Enforce exhaustiveness with a
nevercheck in the switch statement.Test your implementation with example calls for all three response types.
Good luck!