TypeScriptLesson 7 of 16

Literal types and narrowing

A literal type is one exact value, such as "red". A union of literals becomes a short list of allowed options.

Key points

  • type Size = "S" | "M" | "L": the compiler rejects a typo like "XL".
  • Narrowing: after a === or typeof check, TypeScript refines the type in that branch.
  • A switch over literals narrows the type in every case.
  • When every option is handled, no return is needed after the switch.

Example

type Size = "S" | "M" | "L"; function cupPrice(size: Size): number {  if (size === "S") return 2;  if (size === "M") return 3;  return 4; // only "L" is left here} const order: Size = "M";// const wrong: Size = "XL"; // error: "XL" is not assignable to type Size function describe(value: string | number | null): string {  if (value === null) return "empty";  if (typeof value === "number") return `number ${value.toFixed(1)}`;  return `text ${value.toUpperCase()}`;} console.log(`Cup ${order}: ${cupPrice(order)}`);console.log(describe(null));console.log(describe(2));console.log(describe("hi"));

In cupPrice, only "L" is left after the two ifs. In describe each check removes one option: first null, then number, and string is what remains.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

Limit Light to three colours and write next with a switch: red → green → yellow → red. The program prints "1: red", "2: green", "3: yellow", "4: red".

Output

What your program prints appears here.