Unions and Narrowing 28 exercises
Problem

Narrowing Unknown in a Large Conditional Statement

Here we have a parseValue function that takes in an unknown value:


const parseValue = (value: unknown) => {
if (true) {
return value.data.id; // red squiggly line under `value`
}
throw new Error("Parsing error!");
};

The goal of this function is to return the id

Loading exercise

Transcript

00:00 In this exercise, we're going to try to push unknown to its limits just to see how far we can narrow it down. By doing this exercise, you're going to, I think, pull together all of the stuff that we understand about narrowing so far, and we're just going to push, push, push. And we're going to end up with a massive long conditional, but it's going to be worth it. You'll see.

00:19 So we have a pass value function here. And this value is currently typed as unknown, and I want you to keep it that way. And if some conditional inside this little if statement, we want to return value.data.id. And if we don't manage to make this conditional, we're going to throw an error here.

00:39 So your job here is, let's say we pass in data ID into here, then this result should equal string at the end of it. And this means you're going to have to do a lot of narrowing. We need to narrow down the fact that value is a type of object, that it's not null, that

00:57 it has a property of data on it, that that data property is an object and is not null. And then that it has an ID property, which is a string. A lot of code needs to be written, and it's all going to be within this conditional. Good luck.