Enum alternative

2 snippets in TypeScript

TSTypeScript

Literal Types

TS · Type Aliases
Syntax
type Name = "exactValue" | "anotherValue";
type Name = 0 | 1 | 2;
Example
type Direction = "north" | "south" | "east" | "west";
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;

function move(direction: Direction, steps: number) {
  console.log(`Moving ${direction} by ${steps}`);
}

move("north", 3); // OK
// move("up", 3); // Error: Argument of type '"up"' is not assignable
Output
// Literal types restrict a value to an exact set of allowed values

Note Literal types turn strings, numbers, or booleans into specific-value types. Combined with unions, they create powerful enumerations without the overhead of enum. const assertions (as const) automatically infer literal types.

Union Types as Enum Alternatives

TS · Enums
Syntax
type Name = "value1" | "value2" | "value3";
Example
// Instead of enum:
type Theme = "light" | "dark" | "system";

// Object const pattern for when you need both runtime values and types
const THEMES = {
  Light: "light",
  Dark: "dark",
  System: "system",
} as const;

type Theme2 = (typeof THEMES)[keyof typeof THEMES];
// "light" | "dark" | "system"

function applyTheme(theme: Theme2) {
  document.body.dataset.theme = theme;
}
Output
// Union types achieve the same result without enum's quirks

Note Many TypeScript teams prefer string literal unions over enums for simplicity, full tree-shaking, and compatibility with --isolatedModules. The 'as const' object pattern gives you both runtime values (for iteration/lookup) and a derived type - the best of both worlds.

Frequently asked questions

How does TypeScript handle enum alternative?
TypeScript covers this with 2 copy-ready snippets on this page. The "Literal Types" snippet in TypeScript uses `type Name = "exactValue" | "anotherValue";`.
Which code does the TypeScript example use?
The "Literal Types" snippet uses `type Name = "exactValue" | "anotherValue";`, from the Type Aliases section of the TypeScript cheat sheet.
What other TypeScript snippets are shown for "enum alternative"?
Besides "Literal Types", this page also shows "Union Types as Enum Alternatives".
Is there anything to watch out for?
Yes. For "Literal Types": Literal types turn strings, numbers, or booleans into specific-value types. Combined with unions, they create powerful enumerations without the overhead of enum. const assertions (as const) automatically infer literal types.