×

typescript · level 3 · unit 5 · 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

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.