TypeScriptLesson 9 of 16
Enums vs union types
An enum creates a real object that stays in the JavaScript after compiling. A union of literals vanishes without a trace and is usually simpler.
Key points
- A numeric enum counts from zero and maps both ways: Role[1] is "Member".
- A string enum, Open = "open", keeps readable values in logs.
- The union "free" | "pro" | "team" simply disappears after compiling.
- An array with as const gives both a list to loop over and a type: (typeof LEVELS)[number].
- Running .ts directly in Node.js and the erasableSyntaxOnly flag both reject enums.
Example
enum Role { Guest, Member, Admin,}// After compiling, Role is a real object: { Guest: 0, Member: 1, Admin: 2, ... }console.log(`Admin = ${Role.Admin}, 1 = ${Role[1]}`); type Plan = "free" | "pro" | "team"; // disappears after compilingconst plan: Plan = "pro"; const LEVELS = ["low", "medium", "high"] as const;type Level = (typeof LEVELS)[number]; // "low" | "medium" | "high"const level: Level = "high"; console.log(`${plan} / ${level} / ${LEVELS.length} levels`);In JavaScript Role is an object with properties and reverse keys. Plan and Level exist only for checking: not a single line of them is left in the built code.
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.Replace enum Status with a STATUSES array marked as const and a type derived from it, then loop and print three lines: "open: waiting for reply", "pending: in progress", "closed: done".
Output
What your program prints appears here.