External Libraries 9 exercises

Retrieve Function Parameters from an External Library

Let's start by working on the easy bits.

Get the Parameters of fetchUser

To get the parameters of fetchUser, we use Parameters and we pass in typeof fetchUser:

type ParametersOfFetchUser = Parameters<typeof fetchUser>;

This will give us the parameters, including `id

Loading solution


0:01 The solution here is to...First of all, let's do the easy bits. We know how to get the parameters of fetch user. We use parameters. We pass in type of fetch user. What we have here is we end up with ID string, which is really good because then this test passes. It means that when we call fetch user with full name, then we have to pass in ID string.

0:20 If we pass a number there, then it's going to yell at us, which is no good. Not a number itself, but passing in a random number because that's not assignable to string. Then here, this is a bit more complicated. We know that we're going to basically need to extract out the return type of type of fetch user.

0:39 What we end up with there is a promise that wraps ID, first name, and last name. By the way, when we have multiple of these, I like to extract them out into their own thing -- fetch user func, let's say, and say type, fetch user func equals type of fetch user. It just removes a bit of duplication and makes it a little bit easier to see the steps.

1:01 Return type of fetch user with full name, we need to unwrap this promise. We can use Awaited for that. This returns ID, first name, and last name. Now we're getting an error down here because object literal may only specify known properties. Full name is not in the contract that we've agreed because we're typing it here.

1:21 What we can do is we can say this and full name, string. There we go. This is a warm-up exercise to get you back in the mood of understanding these type transformations, understanding how these types flow through the application.

1:35 Also, to look at when you can't extract out a type, this is probably the dance that you're going to have to go through because those types, they don't exist in your application code. You don't control them. Often the only way that you can get information out of them is by doing dances like this.

1:54 Of course, we could extract this out into a type helper. You can check the type transformations module for that.