Tutorials / TypeScript: Beginner to Advanced / Literal types, enums and as const

Literal types, enums and as const

15 min read typescript
Course contents (16 lessons)
  1. Getting started
  2. Why TypeScript? What it is and what it is not
  3. Setting up TypeScript: tsc and tsconfig.json
  4. Core types
  5. Basic types: primitives, arrays, tuples, any and unknown
  6. Typing functions: parameters, returns, optionals and overloads
  7. Objects, interfaces and type aliases
  8. Unions, literals and enums
  9. Union types and type narrowing
  10. Literal types, enums and as const
  11. Classes and generics
  12. Classes in TypeScript
  13. Generics: writing reusable typed code
  14. Built-in utility types: Partial, Pick, Omit, Record and more
  15. Advanced types
  16. Mapped and conditional types
  17. Modules, type imports and declaration files
  18. TypeScript in real projects
  19. Typing async code and API responses
  20. Strict mode and compiler flags that matter
  21. Migrating a JavaScript project to TypeScript
  22. Final project: a type-safe task manager

Literal types

A literal type is a type with exactly one value. The string "north" is a type, the number 3 is a type, and so is true.

let answer: 42 = 42;
// answer = 43;           // Error: Type '43' is not assignable to type '42'

type Method = "GET" | "POST" | "PUT" | "DELETE";

function request(url: string, method: Method): string {
  return `${method} ${url}`;
}

console.log(request("/users", "GET"));
// request("/users", "FETCH");   // Error

A union of literals limits a value to a small set of options. The editor autocompletes the options for you, and typos become compile errors. For a configuration with a few choices, this is simple and effective.

A trap with widening

When you use let or an object property, TypeScript widens a literal to its general type:

const a = "GET";           // type "GET"
let b = "GET";             // type string

const config = { method: "GET" };   // method is string, not "GET"
// request("/x", config.method);    // Error: string is not assignable to Method
console.log(a, b, config.method);

A const keeps the literal. A property in an object does not, because the property could be changed later. There are two fixes: annotate the object, or use as const.

as const

as const tells TypeScript to treat a value as deeply read-only and to keep every literal exactly.

const config = {
  method: "GET",
  retries: 3,
  headers: ["json", "gzip"],
} as const;

type Method = "GET" | "POST";
function request(url: string, method: Method): string {
  return `${method} ${url}`;
}

console.log(request("/x", config.method));  // works: method is "GET"
// config.retries = 4;                      // Error: read-only
console.log(config.headers[0]);             // type is "json"

as const is the standard way to create a fixed list or lookup table where you want precise types.

Deriving a union from an array or an object

Here is a pattern I use constantly. You define the values once, and the type follows from them:

const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];   // "admin" | "editor" | "viewer"

function canEdit(role: Role): boolean {
  return role === "admin" || role === "editor";
}

console.log(canEdit("editor"));   // true
console.log(ROLES.includes("viewer"));   // true
// canEdit("guest");   // Error

typeof ROLES gives the type of the array, and [number] means "the type of any item". You can loop over ROLES at runtime to build a dropdown, and the type always stays in sync.

For an object:

const Status = {
  Active: "active",
  Suspended: "suspended",
  Deleted: "deleted",
} as const;

type Status = (typeof Status)[keyof typeof Status];  // "active" | "suspended" | "deleted"

const current: Status = Status.Active;
console.log(current);

The same name Status is used for the value and the type. TypeScript keeps values and types in separate worlds, so this is allowed and common.

Enums

TypeScript also has a built-in enum keyword. It was added before JavaScript had modules, and it exists in two forms.

Numeric enums count up from zero by default:

enum Direction {
  Up,      // 0
  Down,    // 1
  Left,    // 2
  Right,   // 3
}

const d: Direction = Direction.Left;
console.log(d);               // 2
console.log(Direction[2]);    // "Left"  (reverse mapping)

String enums give each member a text value:

enum LogLevel {
  Debug = "DEBUG",
  Info = "INFO",
  Error = "ERROR",
}

function log(level: LogLevel, message: string): void {
  console.log(`[${level}] ${message}`);
}

log(LogLevel.Info, "Server started");
// log("INFO", "x");    // Error: a plain string is not accepted

Unlike a literal union, an enum is a real object that exists at runtime. The compiler generates code for it.

Enums or unions?

Numeric enums have a known weakness: in older versions any number could be assigned to them, so const d: Direction = 99 compiled. Newer versions check this, but enums still behave differently from the rest of the language. They generate runtime code, they do not work with tools that only strip types (such as Node's built-in type stripping, which rejects enums), and string enums are not interchangeable with plain strings.

For these reasons, many teams now prefer unions of string literals, or as const objects, for most uses. They produce no extra JavaScript, accept plain strings, and are easier to read in logs and JSON. My advice:

  • Default to a literal union or an as const object.
  • Use a string enum if the code base already uses them, or if you want the nominal strictness that a plain string does not give.
  • Avoid numeric enums, unless you need bit flags or to match a protocol.

TypeScript 5.8 added the compiler option erasableSyntaxOnly, which rejects enums, among a few other features. Use it if you want your code to be compatible with plain type stripping.

Template literal types

Literal types can be combined into new ones with the same syntax as template strings:

type Side = "top" | "bottom";
type Edge = `margin-${Side}`;   // "margin-top" | "margin-bottom"

const m: Edge = "margin-top";
console.log(m);

You will see these in libraries for event names and CSS property types.

Common mistakes

  • Expecting an object property to keep its literal. Use as const or an annotation.
  • Passing a plain string to a string enum. It is an error, and a literal union would have accepted it.
  • Using numeric enums for readability. Logging 2 tells you nothing.
  • Duplicating a list of values and a union type. Derive the type from the array.
  • **Forgetting as const on a lookup table.** The values widen to string.

Try it yourself

  1. Create a type Size = "small" | "medium" | "large" and a function that returns a price for each size.
  2. Make an as const array of weekdays and derive a Weekday type from it.
  3. Define a string enum OrderStatus and a function that returns a label for each member. Rewrite it with a literal union.
  4. Create a type EventName using a template literal type, for example "on" + Capitalize<"click" | "hover">.
typescript
const config = {
  method: "GET",
  retries: 3,
  headers: ["json", "gzip"],
} as const;

type Method = "GET" | "POST";
function request(url: string, method: Method): string {
  return `${method} ${url}`;
}

console.log(request("/x", config.method));  // works: method is "GET"
// config.retries = 4;                      // Error: read-only
console.log(config.headers[0]);             // type is "json"

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account