Enums in TypeScript: You're Doing it Wrong

February 14, 2024

Enums in TypeScript: You're Doing it Wrong

Enums in TypeScript can be really tricky. Learn the best approach to dealing with enums with the benefits of serializability, safe mapping, duck typing and value listing.

Approach #1: Numeric Enums

enum Tag {
  git,
  react,
  nextjs,
  nodejs,
}

const tags = Object.values(Tag);

Approach #2: String Enums

enum Tag {
  git = "git",
  react = "react",
  nextjs = "nextjs",
  nodejs = "nodejs",
}

const tags = Object.keys(Tag).filter((item) => {
  return isNaN(Number(item));
});

Approach #3: String Literals

type Tag = "git" | "react" | "nextjs" | "nodejs";
const tags: Tag[] = ["git", "react", "nextjs", "nodejs"];

Approach #4: Advanced String Literals

const tags = ["git", "react", "nextjs", "nodejs"] as const;
type Tag = (typeof tags)[number];

Comparison

EnumsString EnumsString LiteralsAdvanced String Literals
Enums List
Safe Mapping
Duck Typing
Seriaizability