Function Types for Type Aliases in TypeScript
The starting point for annotating the makeChange
function will look like an arrow function. For now, we'll say it doesn't take in a parameter and returns any
:
const modifyUser = (user: User[], id: string, makeChange: () => any) => { return user.map((u) => { if (u.id === id) {
Transcript
00:00 So the way that we annotate a function type on MakeChange here is we first of all say, okay, it's a parameter like normal, and then we can do something like this. Let's just say it's a function that returns any for now.
00:14 So MakeChange now is described as a function that takes in no arguments and then returns anything. Now, what errors is this causing already? Well, we're using MakeChange down here, and MakeChange currently,
00:29 sure, it's grabbing that type there, which is nice, but it expected zero arguments but got one. So how do you add an argument into this type here? Well, just like you would as a function parameter, you say user is user.
00:45 And now, user user, what's going on here is we can now return the type that we want as well. So it's currently returning any, but that's giving us an error there, because actually we're expecting it to return user, because otherwise this TS expect error wouldn't be lighting up, and we get an error sort of down there.
01:02 So let's say user user, let's make it return user as well. So now when we're doing some modifications in here, we're going to get autocomplete for the things that we want to use here. Very, very cool. And there's one more thing we can do here. We don't have to do this, as you can see, but we can just extract it out into a type of its own,
01:22 because of course a type alias can be anything. And let's say make change func is a user that returns a user, and now just stick in make change func in here, and that all looks very, very nice. So this is a way that you can express function types for callbacks, for modification functions like this,
01:41 and even for typing functions themselves. Very cool.