Unions and Narrowing 28 exercises
Problem

Narrowing with `in` Statements

Here we have a HandleResponse function that takes in a type of APIResponse, which is a union of two types of objects.

The goal of the HandleResponse function is to check whether the provided object has a data property. If it does, the function should return the id property. If not, it sh

Loading exercise

Transcript

00:00 In this exercise, we have a HandleResponse function, which takes in a type of an API response. Now this syntax might look a bit confusing in the API response, but really it's a union between two different objects. We've either got this object, where you can have a key of data, which is an ID of string, or we have an object which just has an error property on it, which has string.

00:21 So inside here in HandleResponse, we're basically trying to check if we're in the branch with the data attribute on it. And if we are, then we need to return the ID there. Otherwise, we want to throw an error with the response.error to make sure we're in that branch. But we've got a couple of errors showing here.

00:40 The first error, we've got property data does not exist on type API response because property data does not exist on the error branch. Okay, that's kind of confusing. And this one, we've got the reverse error happening. Probably error does not exist on type API response. We've also got an unreachable code detected error here too,

01:00 because we've just got an if true happening inside HandleResponse. So this if true, then we need to change this to find the proper condition to do the narrowing here to make our tests pass, because our tests down the bottom are also not working. So that's your job is to try to find out the right thing

01:18 that you can put inside this if condition to make this all work, make it happy on the type level and make it work on the runtime level. There is a specific syntax I'm thinking about. Good luck.