TypeScript theorytheory 0/50 · 0%
Types · easy

8. Enums

Named sets of constants, numeric or string-based.

`enum` defines a named set of constant values. Numeric enums auto-increment from 0 unless given explicit values; string enums require every member to have a string value, which makes them clearer in logs and debugging.

ts
enum TxStatus {
  Pending,
  Confirmed,
  Failed,
}

enum Network {
  Mainnet = "mainnet",
  Testnet = "testnet",
}

let s: TxStatus = TxStatus.Confirmed; // 1
let n: Network = Network.Mainnet;     // "mainnet"

Many teams prefer a union of string literals (`type Network = "mainnet" | "testnet"`) over enums, since literal unions produce no extra runtime code and work more predictably with plain JS objects — but enums remain common in codebases that want an explicit, iterable namespace.

Check your understanding

  1. 1. What value does the first member of a numeric enum get by default?

  2. 2. What must every member of a string enum have?

  3. 3. What is a common lightweight alternative to enums?