typescript · level 3 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Helper types change the letters of a literal type.
TypeScript has four built-in helpers for literal string types. is "TEA", and Lowercase does the reverse. is "Tea", changing only the first letter, and Uncapitalize turns it back.
They shine inside template literal types. If your fields are "name" | "email", then set${Capitalize<Field>} is "setName" | "setEmail". Add a field and its setter name follows.
type Field = "name" | "email";
type Setter = `set${Capitalize<Field>}`;
type Shout = Uppercase<"stop">;
const setters: Setter[] = ["setName", "setEmail"];
const sign: Shout = "STOP";
console.log(setters, sign); These helpers only work on types. At runtime you still need .toUpperCase().
guess first
One small letter. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
type Field = "name" | "email";
type Setter = `set${Capitalize<Field>}`;
const call: Setter = "setname";
console.log(call);
your turn
Your turn. Name the traffic lights.
Choose the helper that makes every letter a capital, then list both light names that fit the pattern.
fix it
The pet getters will not match. Fix the type.
- Read the error. Which strings does
Getterallow right now? get${Pet}gives"getcat"and"getdog", all small letters.- On line 2, use
Capitalize<Pet>inside the pattern.
nailed it
your type names change case on command. :D
Uppercase,Lowercase,CapitalizeandUncapitalizework on literal types.- Combine them with patterns, like
set${Capitalize<Field>}. - They change types only; values still need string methods.
new words in your collection
- Uppercase
- Capitalize
This lesson isn’t saved. A free account remembers every lesson you finish.