Deriving Types From Values 15 exercises
solution

Flowing Types with the keyof Operator

Instead of manually specifying a union type for the inputs Record, we can use keyof FormValues to derive the types automatically:


const inputs: Record<
keyof FormValues, // "name" | "email" | "password"
{
initialValue: string;
label: string;
}

Think of the `key

Loading solution

Transcript

00:00 So the solution here is instead of name or email or password, we want to derive this from the form values and we can use KeyOfFormValues to do exactly that. So KeyOfFormValues is exactly the same as this type here as name or email or password. How amazing is that?

00:20 So if you think about this, we've now created a flow of types where form values is like the source of the river. And then these flow down into anywhere they're referenced, so into this input. This means that if I add something else to the upstream up there to the source of the river, I say phone string,

00:42 I'm now going to have to add that into this object I have of name, email and password. And if I look in here, I get autocomplete for phone. Look at that. So now initial value, I need to specify that and a label 2 of phone. Beautiful.

00:57 So this is kind of your first intro into the way that types can kind of flow down into other types. And now I don't need to add phone into this union down here. It's automatically added for me. TypeScript is so good for this. If I just reset everything, everything just works beautifully.

01:14 It is so nice to use and it means now that I can just have a single interface like the root of my app and derive other things from it.