Conditional Types and Infer 10 exercises

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:

type GetParserResult<T> = T extends {
parse: () => infer TResult
? TResult
: T extends () => infer TRe

Loading solution


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.