Unions and Narrowing 28 exercises

Gotchas When Narrowing a Map in TypeScript

Let's take a look at another gotcha with narrowing in TypeScript.

Here we have a processUserMap function that takes in an eventMap that is a Map containing a key of string and a value of Event. The Event has a message string on it:

type Event = {
message: string;

Loading exercise


00:00 In this exercise, we're going to look at another kind of small gotcha when it comes to narrowing in TypeScript, where we have this processUserMap function, which takes in an event map, which is a map. And that map has a key, which is a string, and it also takes an event as the value. So this event up here has message string on it.

00:19 So what we're trying to do here is we're trying to say if eventMap.hasError, then we grab that message from the event map and then throw it. So your job here is to work out why this is failing. Why wouldn't this just work out of the box? Because we're checking up here if the event map has something with error on it.

00:38 Surely it should know that eventMap.getsError, like the map would have that error on it. So why isn't this working? Well, that's your job. And see if you can also refactor this to a way where we don't change anything about the outside of the function, but we still retain the behavior. But TypeScript's sort of narrowing works with us instead of against us. Good luck.