February 14, 2024
Info
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
Enums | String Enums | String Literals | Advanced String Literals | |
---|---|---|---|---|
Enums List | ||||
Safe Mapping | ||||
Duck Typing | ||||
Seriaizability |