×

typescript · level 2 · unit 2 · lesson 4

  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 picks one from a menu of values.

A long chain of else if checking one value gets hard to read. A switch looks at one value and jumps to the matching case. Each case names a value, then the lines to run, then break to leave the switch.

The part runs when no case matches, like the else at the end of a chain. Switches suit literal types well, because the checker knows every value on the menu.

When a case ends in return, the function stops there, so no break is needed. Short cases can sit on one line.

type Weather = "sun" | "rain" | "snow";
function pack(weather: Weather): string {
  switch (weather) {
    case "sun": return "sun cream";
    case "rain": return "an umbrella";
    default: return "a warm hat";
  }
}
console.log(pack("rain"));
console.log(pack("snow"));

Write each case value exactly as it appears in the literal type.