Type Transformations Workshop (9 exercises)
solution

Two Methods for Extracting the Result of Multiple Possible Functions

There are two solutions for this challenge:

Solution 1 - Use Ternaries

The first solution is to write a long conditional where you infer the result from each possible function:

This makes the tests pass, but it's a fairly ugly solution.

Solution 2 - Use a Union Type

The preferred solution is to use a union type instead.

We can say that T extends either an object with parse, an object with extract, or a function. Each of these branches has its own infer TResult.

If T extends any of the types, infer its TResult, otherwise return never:

Using a union type gives us the same expressiveness as the ternary solution, but is much more readable.

Transcript

[0:00] This has two solutions. I imagine that you probably found this one. In this solution, we have a T extends parse. We infer the result. We return the result. If that's not right, then if we have a function that just returns infer TResult, then we return the two.
[0:18] It basically walks through each one of these possible cases and returns the TResult in each of the cases. This makes all of our tests pass. It is a perfectly fine solution, but it's pretty ugly. You've got this long ternary here. You've got three different elements in it. It's not very fun.

[0:38] My preferred solution is actually to use a union type instead. What you can do here is you can say T extends either this branch or this branch or this branch. You can specify an infer TResult in each branch.

[0:53] That means you basically get the same expressivity as you had in the previous version, but the syntax is much more readable because you're basically saying, "OK, if T extends any of these, then we're going to grab the results and pull it through." This is a really, really useful case for often avoiding these really long ternaries and instead just grabbing the thing that you need.