Enums
An enum declares named constants. Ordinary enums emit a runtime object; const enums have different compilation behavior.
Inspect the generated behavior of enums before using them to represent alternatives.
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.