Deriving Types From Values 15 exercises
solution

Use the Parameters Type to Extract Function Parameters

The Parameters type is a global type helper in TypeScript that allows you to extract the parameters from a function type.

The fastest way to solve this challenge is to use the Parameters type helper, which is available globally in TypeScript. It expects a function as its input, so passing a st

Loading solution

Transcript

00:00 Okay, the way to solve this, the fastest way to do it, is just to say parameters using a global type that's available in TypeScript. And then we can pass in make query, except, ooh, we can't quite do that. What parameters does is it extracts out the parameters

00:19 from a function type. And make query isn't a function type, it's a value. So we need to say type of make query. And now we can see that make query parameters, if we hover over it, it's basically this shape here. It's a tuple with URL string at the start. It's got some names as well, which is quite nice.

00:39 And then it has these opts inside here. So parameters, you have to pass in a function into parameters, so I can't pass it like an object type, for instance, a string like this. It's gonna yell at me if I try to do that. It doesn't provide any match for the signature function args any, any. Okay, fine, so I have to pass in some kind of function

01:00 and it extracts the parameters from that function. This is extremely useful. And if, for instance, I just want to just grab the second parameter, type second parameter like this, then I can just do make query parameters and just pass in the index of that. So now we end up with this options thing here,

01:18 which is really, really nice. So this is super cool when you have a function that's in a third party library that you don't control, but you want to extract a type from. So this can be a super duper useful type helper. And it's also useful in sort of more complicated TypeScript too. So parameters, very, very useful type helper available globally in TypeScript.