Enums
A task's status is one of exactly three things: to do, in progress, or done. Scatter the strings "todo", "doing", "done" across a codebase and sooner or later someone writes "Done" or "finished". An enum gives the allowed values names and one home.
The rule
An enum names a fixed set of constants, and it exists at runtime.
A string enum gives each member an explicit text value:
enum Status {
Todo = "todo",
Doing = "doing",
Done = "done",
}
let s: Status = Status.Done;
s = "done"; // error: a plain string is not a Status
s = Status.Todo; // fineA numeric enum leaves out the values, and members count up from 0:
enum Priority { Low, Medium, High } // 0, 1, 2
enum Level { A = 1, B, C } // 1, 2, 3Unlike almost everything else in TypeScript, an enum is not erased. It compiles to a real JavaScript object, so you can use it as a value, for example Object.values(Status) to fill a dropdown. Numeric enums also get a reverse mapping: Priority[2] gives the name "High". String enums do not have one.
const enum is a variant whose members are inlined as plain values and no object is emitted, trading that runtime object for smaller output.
The popular alternative is a union of string literal types:
type Status = "todo" | "doing" | "done";
let s: Status = "done"; // a plain string, still checkedThis is fully erased, adds no code, and accepts ordinary strings, which is convenient when values arrive as JSON. Many teams prefer it; others like enums for the named, iterable object. Both catch "finished" as an error.
The shortcut
Ask "Do I need the list of values while the program runs?"
- Yes (loop over them, show them in a menu) → an enum gives you that object.
- No, I just need the compiler to reject wrong values → a union of literals is lighter.
Name the set
Three statuses, never more without a code change. A fixed set, so an enum or literal union fits.
The trap with numeric enums: saving 2 to a database and later inserting a new member in the middle shifts every number after it. String values are safer for anything stored.
Drills
Answer fast — trust the rule.
In enum Priority { Low, Medium, High }, what is the value of Priority.High?
What does an ordinary enum become after compiling?
In enum Level { A = 1, B, C }, what is Level.C?
With a string enum Status, why is let s: Status = "done"; an error?
Which feature gives you a checked set of statuses with no runtime code at all?
Remember
- An enum names a fixed set of constants, and it exists at runtime.
- Ask "do I need the values at runtime?" — yes suggests an enum, no suggests a literal union.
- Trap: stored numeric enum values shift if members are reordered; prefer string values.
