Challenge 2: Brand a Validated Password — Possible Solution ==================================================================== type Brand = T & { readonly __brand: TBrand }; type StrongPassword = Brand; function toStrongPassword(input: string): StrongPassword { if (input.length < 12) { throw new Error("Password must be at least 12 characters long"); } if (!/\d/.test(input)) { throw new Error("Password must contain at least one digit"); } return input as StrongPassword; } function hashAndStorePassword(password: StrongPassword): void { // In a real app this would call bcrypt/argon2 — the point is that by // the time a value reaches this function, it's guaranteed to have // already passed the strength check. console.log(`Hashing password of length ${password.length}`); } // --- Usage --- const strong = toStrongPassword("correcthorse123battery"); hashAndStorePassword(strong); // ✅ compiles — proven strong // hashAndStorePassword("weak"); // ❌ a plain string, even a strong-looking one, is not a StrongPassword — // it MUST be passed through toStrongPassword() first. try { toStrongPassword("short1"); // too short } catch (err) { console.error((err as Error).message); // "Password must be at least 12 characters long" } try { toStrongPassword("nodigitsinthisone"); // long enough, but no digit } catch (err) { console.error((err as Error).message); // "Password must contain at least one digit" } WHY THIS WORKS -------------- - toStrongPassword() throws before ever producing a StrongPassword value — there is no code path where a StrongPassword exists without having passed both the length check and the digit check. - hashAndStorePassword() accepts only StrongPassword, not string — any caller trying to pass an unvalidated string gets a compile error, forcing every caller in the codebase through the one validating constructor rather than trusting each call site to remember the rule. - This mirrors the chapter's Email example closely: a real runtime check (here, plain string methods instead of a zod schema) is what makes the brand meaningful — the brand itself does nothing without it.