typescript · level 3 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Template literal types describe the shape of a string.
In Level 1 you built strings with backticks and ${}. The same idea works for types. Wrapped in backticks, ${number}px is a : any string made of a number followed by px, like "12px". The text "twelve px" is rejected before the code runs.
Put a union inside and you get every pairing. The pattern ${Size}-${Colour} with two sizes and two colours allows four strings, and you never write a single one out by hand. Add a colour and the new pairings appear.
type Pixels = `${number}px`;
type Size = "small" | "large";
type Colour = "red" | "blue";
type Shirt = `${Size}-${Colour}`;
const gap: Pixels = "12px";
const shirts: Shirt[] = ["small-red", "large-blue"];
function margin(value: Pixels): string {
return `margin: ${value};`;
}
console.log(margin(gap), shirts); ${string} inside a pattern means any text at all, even none.
guess first
Two brand colours. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
type Hex = `#${string}`;
const brand: Hex = "#ff6600";
const accent: Hex = "ff0066";
console.log(brand, accent);
your turn
Your turn. Book a hotel room.
Build the Room pattern from a floor, then a dash, then a wing. Then book a room that fits it.
fix it
The release will not ship. Can you fix it?
- Read the error:
TS2345says"1.4"does not fit the typeVersion. - Compare
"1.4"with the pattern on line 1. What must every version start with? - Change the argument on line 5 to
"v1.4", then run.
nailed it
your strings follow the rules now. :D
${number}pxallows only strings shaped like"12px".- A union inside a pattern makes every pairing for you.
- Wrong-shaped strings are caught before the code runs.
new words in your collection
- template literal type
This lesson isn’t saved. A free account remembers every lesson you finish.