The Weird Parts of TypeScript 13 exercises

Typing Arrays of Functions with Object Params

To start solving this challenge, let's start by hovering around to see the type definitions we're working with.

Hovering over the loggers.forEach(), we can see that func is a union between two different types of functions:

const logAll = (obj) => { // red squiggly line under obj

Loading solution


00:00 Okay, let's take a look at some of these little hovers that we've got going on. So, loggers.foreach func. If we take a look at this, we can see that func is a union between two different types of functions. One, which takes in an ID string, and another one which takes in a name string.

00:16 This makes sense, because when we call the array, we don't know which one we're getting at which time. And you might think, okay, that's cool, that means that we can basically pass in a union to the object. We can say it's either going to be ID string or name string. Perfect, because we're calling a union function, so we can just pass in a union. But it doesn't work like that.

00:35 If we look at this func, the second one, then we can see that it kind of gets mashed together. The union of functions turns into one function with one call signature that says it's a function which takes in an object which has ID string and name string.

00:51 So, when we call this function now, it has to be a function that contains all of the possibilities of things being passed into it. So, it has to contain ID string and it has to contain name string. So, this means that we can't use a union on this, we have to use an intersection.

01:08 Or, of course, we could just say ID string, name string, just a normal object being passed in. This is really interesting and makes total sense, because if we were to just call this and we were just to say log ID, obj, then, of course, TypeScript wouldn't yell at us even though there's an excess property being passed to it, right?

01:26 And then log name, of course, it would do the same thing here. So, this behavior makes sense when we think about how functions actually behave in JavaScript. And this is going to come up in, I think, the next exercise too.