×

typescript · level 3 · unit 7 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A stops look-alike values getting mixed up.

An email and a postcode are both string, so TypeScript happily lets you pass one where the other belongs. A branded type adds an invisible label: string & { readonly brand: "Email" }. Plain strings no longer fit, only strings that carry the brand.

No real string has a brand property, so you add it with a : text as Email tells the checker to trust you. Keep that in one that checks the value first. Then every Email in your program has been checked.

type Email = string & { readonly brand: "Email" };
function toEmail(text: string): Email | null {
  if (!text.includes("@")) {
    return null;
  }
  return text.trim().toLowerCase() as Email;
}
function sendWelcome(to: Email): void {
  console.log(`Welcome email sent to ${to}`);
}
const email = toEmail("  Ada@Example.com ");
if (email) {
  sendWelcome(email);
}

The brand only exists for the checker. At runtime an Email is a plain string.