typestar

Enums and the alternative in TypeScript

What an enum gives you, and why a const object often beats it.

enum Level {
  Debug,
  Info,
  Warn,
}

const enum Inlined {
  Yes = "yes",
}

const LEVELS = {
  debug: "debug",
  info: "info",
  warn: "warn",
} as const;

type LevelName = (typeof LEVELS)[keyof typeof LEVELS];

function log(level: LevelName, message: string): string {
  return `[${level}] ${message}`;
}

console.log(Level.Info, Level[1], Inlined.Yes);
console.log(log("warn", "slow"), Object.values(LEVELS));

How it works

  1. A numeric enum is bidirectional and emits real code.
  2. A string enum is nominal: two identical strings are not assignable.
  3. A const object with as const is erasable and structurally typed.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
399
Tokens
116
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 82 seconds.

Type this snippet

Step 4 of 4 in Primitives & literals, step 4 of 23 in Types & annotations.

← Previous Next →