Combine Type Helpers with Branded Types
Let's work through the solution for our problem.
Typing the Valid Brand
Valid type helper needs to be typed:
type Valid<T> = unknown;
T that is being passed into
Valid should in turn be passed into
As a refresher, here's the source for our
0:00 Let's work on the solution. We know that we're going to need to type this valid brand in some way. We think about type helpers and how they work. We're basically taking in that T, which is going to be the thing that we're going to type. We need to pass it into brand, probably. A good way to think about it is that we have our T brand here.
0:20 We probably don't need to make this T brand generic. We can just use a single brand which is going to be valid. Then we pass that T in. We should be able to call it with brand T, and then valid here. It doesn't really matter what this is as long as there's a difference between valid and invalid.
0:37 We got our valid brand here. What we can do is it's still erroring down here, that's because this validated values is just still raw password values. It hasn't been marked with valid yet. Here we can see that this now needs to be valid password values. Let's do that. Inside validate password here, we need to say "As valid password values."
1:05 Now what happens is when we get back these validated values, they are valid or marked as valid, which is super nice. Then this create a User on API works now. This error is properly working, too, which is really, really cool. We're getting this nice error because we haven't...Isn't that a lovely error message.
1:26 Argument of type password values is not assignable to parameter of type valid password. So good. This is a more reusable way of marking your things as valid or invalid. It works at the object level instead of at the individual primitive level, a string or number level. Really, really cool. A really nice way to get started with branded types.