Unions and Narrowing 28 exercises

Refining Types with Discriminated Unions of Tuples

Let's look at how a discriminated union of tuples can be used to represent an API response.

We'll be working with a fetchData function that returns a promise that resolves to an ApiResponse tuple that consists of two elements: The first element is a string that indicates the type of the respon

Loading exercise


00:00 In this exercise, instead of talking about a discriminated union of objects, we're going to look at a discriminated union of tuples. We have a FetchData function, which is an async function which returns a promise containing an API response. This API response is a tuple. Now, that tuple currently has two members.

00:18 The first member is a string, and the second member is an array of users or a string. Let's look and see what we mean by that. The first way that this tuple can resolve is basically by having, okay, we have a tuple which contains error as the first member of the tuple,

00:36 and the second is a string containing the error that occurred. Then down the bottom here, we have another one which is success, and that then returns the data. And you can start to see that we've modeled our API response a little bit inaccurately. We have kind of several possibilities. We can pass stuff into this API response

00:54 that isn't error or success, and we can do the wrong combinations too. So we can pass in an error when we're in fact returning the data. So your job here is to figure out how you can change the type of this API response to be more accurate, probably using a discriminated tuple or a union of multiple tuples.

01:11 And then inside the example func down the bottom, we want to check that this is working. And you notice that when we fetch the data here, we fetch the data and we get back status and value, we want to check if the status equals success, we want to console log the value, and we want in that case,

01:30 the type of value to be an array of users. Otherwise, we want the value to be a string here. So that's your job. And this is, I think you'll have all the pieces you need to understand this and get it right. And notice as you're going through it, how TypeScript is narrowing and the clever things it's doing, and I'll see you in a minute.