×

typescript · level 2 · unit 2 · lesson 2

  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 allows only the exact values you list.

A string box takes any text at all, typos included. Often only a few values make sense. A coffee comes in small, medium or large, and nothing else.

A literal type is one exact value used as a type, like "small". Join several with | and you get a short menu: type Size = "small" | "medium" | "large";. Anything else, like "huge" or "meduim", is a TS2322 before your code runs.

A const box keeps its literal type. After const size = "small"; the checker knows it is exactly "small", not any string.

type Size = "small" | "medium" | "large";
type Drink = { name: string; size: Size };
const order: Drink = { name: "latte", size: "medium" };
console.log(`One ${order.size} ${order.name}, please.`);
order.size = "large";
console.log(`Make that ${order.size}!`);

Literal types work with numbers too, like type Dice = 1 | 2 | 3 | 4 | 5 | 6;.