typescript · level 3 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Charge in pence. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
type Pence = number & { readonly brand: "Pence" };
function toPence(pounds: number): Pence {
return Math.round(pounds * 100) as Pence;
}
function charge(amount: Pence): string {
return `Charging ${amount}p`;
}
console.log(charge(toPence(2.5)));
console.log(charge(250));
your turn
Your turn. Brand a postcode.
Use a type assertion to give the cleaned text its brand, then type a postcode with a space in it.
fix it
The wrong order is about to be cancelled. Fix it.
- Read the error:
TS2345says aUserIdcannot go where anOrderIdis needed. - Both are strings underneath, but their brands differ. The brand caught a real bug: the wrong ID.
- On line 14, pass
ordertocancelOrderinstead ofuser.
nailed it
look-alike values can no longer swap places. :D
- A brand like
string & { readonly brand: "Email" }makes look-alikes different. - Only a smart constructor should use
asto add the brand. - Brands exist only for the checker, so they cost nothing at runtime.
new words in your collection
- branded type
- type assertion
- smart constructor
This lesson isn’t saved. A free account remembers every lesson you finish.