Deriving Types From Values 15 exercises
Problem

Creating Types from Complex Function Parameters

Here we have a makeQuery function that takes two parameters: a url and an optional opts object.


const makeQuery = (
url: string,
opts?: {
method?: string;
headers?: {
[key: string]: string;
};
body?: string;
},
) => {};

We want to specify these

Loading exercise

Transcript

00:00 We've been talking about deriving types from values, but what if that value is kind of complicated and you only want a certain part of it? Well, we have a function here called makeQuery, and makeQuery takes two parameters, takes in a URL, which is a string, and an opts thing here, which is basically a big object

00:18 with a bunch of different stuff. Now, we want to say that makeQuery parameters here, we want it to be a tuple, which has the first argument of string in there, so I can actually just sort of manually do this if I want to, string, and then the second member of that tuple is going to be this big object there.

00:37 And once I've done that, is that correct? Oh, in fact, no, it's nearly correct because I want this to be optional as well. So I want it to be an optional member of the tuple. So I want this to be our ending situation here, except of course, I now have two sources of truth. I have the types up here,

00:56 and I have this type down there. And I want you to imagine for a moment that you do not control this function. Let's say this function is coming from a third-party type, because obviously the thing that you might want to do is just capture this options, put it inside a type, opts, like this, and then you've got a single source of truth for both of these types here.

01:15 So we can say opts, and bam, it's all done. But let's say you can't do that. You cannot extract this type manually. What can you do? And there is a type helper that can help you out, and the only thing I want you to do is change this line here, which is the make query parameters type.

01:34 And the type helper is called the parameters type helper. Good luck.