Type Predicates and Assertion Functions 6 exercises
solution

Checking for Validity with Brands and Type Predicates

The solution is to annotate the isValidPassword function with a type predicate of values is Valid<PasswordValues>:


type Valid<T> = Brand<T, "Valid">;
interface PasswordValues {
password: string;
confirmPassword: string;
}
const isValidPassword = (
values: PasswordValues,
)

Loading solution

Transcript

0:00 The solution for this is to take this isValidPassword and annotate it with values is valid password values. Isn't that nice. This means that when we use it inside an if statement, it makes those password values valid. Very, very cool.

0:18 If we were to determine this outside of the if statement, then it would just be normal password values. This changes it to add the brand to it. This means that branded types are really, really nice with type predicates because you can just, you don't need to do any as stuff here.

0:34 There's no assertions going on or casting or anything like that. It's just literally values is valid password values, which is pretty nice.