Validate Types with Brands and Assertions
The solution is to change assertIsValidPassword
to give it asserts values is Valid<PasswordValues>
:
function assertIsValidPassword( values: PasswordValues,): asserts values is Valid<PasswordValues> { if (values.password !== values.confirmPassword) { throw new Error("Passw
Transcript
0:00 The solution here is to change assertIsValidPassword and to give it asserts is, sorry, values is valid PasswordValues. What this does is it means that when we use it, then these values end up being valid password values.
0:19 Just like the type predicate version that we saw in the previous exercise, this is really, really nice. It produces this lovely API which, first of all, reads really nicely. Actually, surprisingly for a Typescript annotation. asserts values is valid PasswordValues.
0:35 The brand gives it a sense of identity, means that you don't need to do any casting here again, and it just slides in. It's just so lovely. Of course, if we don't do this, then we're going to get an error here because password values is not assignable to parameter of type valid PasswordValues.
0:52 You get lovely errors here too. This again, this is a really nice solution that you can bring branded types in and use assertion functions with them in order to get this really smooth API.