Unions and Narrowing 29 exercises
Problem

Discriminated Booleans

In this exercise, we're revisiting the ApiResponse type and fetchData function that we've seen before.

The ApiResponse has been updated to be a tuple where the first member is a boolean, and the second member is either a user array or a string:


type ApiResponse = [boolean, Use

Loading exercise

Transcript

00:00 In this exercise, we're going to look at the FetchData function again that we've seen before. And we've refactored it back to an API response that kind of has a user array or string in the second member of the tuple, but it has a boolean in the first one. So this is no longer a discriminated union, it's just a tuple type.

00:19 But if we go down to the bottom, we can see that in our example function here, instead of destructuring the status, we're now just destructuring a succeeded value, which is currently a boolean. And you can see here that if it does succeed, then we're checking if the value is this.

00:36 Otherwise, we're checking if the value is a string instead. So your job is to work out how to type this API response to better represent these states. And this, I think, is a simple exercise, but it really clarifies something interesting about discriminated unions. Good luck.