Branded Types 7 exercises
solution

Assigning Branded Types to Values

The right way to think about this solution is that validateValues is the way we turn our values from raw values into things that we know are Email and Password.

The values we return shouldn't be email: string and password: string.

They should be email: Email and password: Password.

Loading solution

Transcript

0:00 The right way to think about the solution is that validateValues is the way we turn our values from raw values into things that we know are email and password.

0:10 The idea is that when these are called, that the validated values shouldn't be email string and password string, they should be actually these values here. They should be email email and password password.

0:23 We can't add this as a return type here because actually, these are incompatible. We haven't done any conversion from an invalid value to a validated value. If we add them here as email and as password, whoops, as password, then we know that everything is correct here.

0:41 This is really cool because what it means is that this then acts as a conversion function, taking the invalid values and churning out the actual values.

0:53 It means then that we can really trust that everything that's, if we have like something that's being passed around our app like this email, we know that it's going to be an email wherever it gets passed in.

1:03 This gives us a lot of confidence in our code, and it means that when we create the user on the API, imagine if this code wasn't here and we were just passing in the invalid values here, string password string.

1:15 It would be really easy to think, "Oh yeah, createUserOnAPI. That validates its values before they get sent to the API, doesn't it? It definitely does." Well, no, it doesn't. Having it like this means that you guarantee that your code is correct and it gives you a sense of logical surety.

1:33 That's a logical confidence that Typescript doesn't usually give you.