Type Transformations Workshop (4 exercises)

Transform a Discriminated Union with Unique Values to an Object

This exercise is a more difficult version of one we saw earlier in the workshop.

We start with the following:


Your challenge is to update RoutesObject to match how it is seen in the test:

Hint: When mapping, check that if the search key is present. If it is, return it. Otherwise, return never. You'll want to use infer as well.


[0:00] [0: 00] This exercise is like a more difficult version of one that we've seen before. In the one that we saw before, we had a Route here, which was a discriminated union, and each route had a search object on it like this, which was an empty object, basically. This makes things easier because, when you're mapping over this, you know that search is always going to be there.
[0:27] [0: 27] What you'll see is that, when you try to create a RoutesObject, which is basically going to be a keyed object of this, then you're going to see that it's harder to extract the search from the place that you think it's going to be. You're going to need a bit of infer here.

[0:42] [0: 42] We're going to need definitely some map types. I can't remember whether it uses as or not, but I think that's enough of a clue to get you started. Your goal here is basically to say, "OK. When we have this key, because it has a search property on it, then we want to return that search property. Otherwise, we're going to return never." Best of luck.