Sub topic 3
Enums or Literal Unions: How to Choose
Assume you know basic TypeScript types, functions, object literals, and switch statements. A fixed set of values can be modeled with a literal union or an enum.
Enums or unions
A literal union is usually the simplest choice when values are already strings or numbers:
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction): void {
console.log(direction);
}
move("up");An enum creates a named value object at runtime:
enum Direction {
Up = "up",
Down = "down",
}
move(Direction.Up);| Choose a literal union when | Choose an enum when |
|---|---|
| Values cross JSON or API boundaries | You need a runtime namespace |
| You want plain string literals | Existing code requires enum members |
| Minimal emitted JavaScript matters | Named values improve the API |
Unions work naturally with JavaScript libraries and serialized data. Enums can provide centralized names, but they add runtime behavior and may require conversions at boundaries.
Exhaustive checks with `never`
A discriminated union has a literal field that identifies each variant. Assigning the default branch to never makes missing cases a compile-time error.
type Result =
| { kind: "success"; value: string }
| { kind: "failure"; error: Error };
function message(result: Result): string {
switch (result.kind) {
case "success":
return result.value;
case "failure":
return result.error.message;
default: {
const impossible: never = result;
return impossible;
}
}
}If you later add a "pending" variant, the assignment to never fails until the new case is handled.
Template literal types
Template literal types construct unions from other unions:
type Event = "click" | "focus";
type HandlerName = `on${Capitalize<Event>}`;
// "onClick" | "onFocus"They are useful for typed event names, property names, and command formats.
Const enums
A const enum usually inlines members during compilation, so it emits no enum object:
const enum LogLevel {
Info,
Error,
}
const level = LogLevel.Error;Inlining can reduce runtime code, but it removes runtime access and can cause problems for library consumers, isolated compilation, or mismatched declaration and implementation versions. Use ordinary enums or unions when published code must be predictable across build tools.
> callout note > Prefer literal unions for data values. Use enums when a runtime object or an established enum-based API is part of the requirement. > end
Validating constants with `satisfies`
satisfies checks a value against a type without replacing its inferred type:
const colors = {
error: "#f00",
success: "#0f0",
} satisfies Record<"error" | "success", string>;
const upper = colors.error.toUpperCase();The object must contain valid keys and string values, while colors.error remains a string.
Exercise
Which model should you choose for values received as strings from a JSON API?
Show answer
Use a literal union, such as "draft" | "published", because it matches the serialized data directly.