The Weird Parts of TypeScript 13 exercises

Unions of Function Return Types

Let's look at how unions of function return types behave.

Consider two functions idToUppercase and idToInt. The former accepts an object with a string id and converts it to uppercase, while the latter converts it into a number. Both functions are then added to an array called funcs:

Loading explainer


00:00 Let's take a look at how unions of function return types behave. We have an id2 uppercase function, which takes in an id string and returns a string. id2 integer basically takes in an id string and returns a number. And then we have a set of functions, one of which returns a string, one of which returns a number. Then we have a resolveAll function,

00:19 which if we look at it, returns an array of either string or number by mapping over each function and then calling that function. If we look at the function here, you can see that the function is resolved to an object, which has an id string on it, fantastic, and then returns string or number.

00:37 So finally, the result after we resolve all of this is an array of string or number. So if you think about it, then when you have two, if you have unions of functions, then the parameters get intersected together and the return types get unioned together.

00:55 So we're not getting never at the end of this function, we're getting a union of string or number. And of course, this makes sense, right? So if we were to just like return, let's say id2 uppercase or id2 int obj and then return id2 uppercase obj, then this of course checks out

01:14 because the result would still be the same. It doesn't matter whether we're using a union or not, we still get the same behavior. And if we just, if I go back to all of this and I remove one of those, if I remove id2 int from the functions, then of course this is just an array of strings because that's the only thing that can be produced from these functions.

01:33 So that's your mental model how it should be is when you have a union of functions, the parameters get intersected and the return types get unioned.