Literal Types

Restrict a value to a specific set of exact values.

Syntaxlet dir: "left" | "right";

A literal type uses an exact value as the type. Instead of allowing any string, you can allow only certain strings.

On their own they are limited, but combined with unions they become powerful — for example a status that can only be "active", "paused", or "done".

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A HTTP helper function accepts only the literal strings 'GET', 'POST', 'PUT', 'DELETE' as the method parameter.
  • A UI theme switcher restricts the theme variable to 'light' | 'dark', preventing any other string assignment.
  • A card suit type is defined as 'hearts' | 'diamonds' | 'clubs' | 'spades', making exhaustive switch checks possible.

More examples

String literal union type

Defines a string literal union so the function only accepts one of four specific direction strings.

Example · ts
type Direction = 'north' | 'south' | 'east' | 'west';

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

move('north', 3);
move('up', 1); // Error: Argument of type '"up"' is not assignable

Numeric literal union

Uses a numeric literal union to constrain a dice roll result to exactly the integers 1 through 6.

Example · ts
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;

function rollDice(): DiceRoll {
  return (Math.floor(Math.random() * 6) + 1) as DiceRoll;
}

Literal type with const assertion

Uses as const to narrow an object's values to literal types and derives a union type for reuse across the codebase.

Example · ts
const STATUS = {
  PENDING: 'pending',
  DONE: 'done',
  ERROR: 'error',
} as const;

type Status = typeof STATUS[keyof typeof STATUS]; // 'pending' | 'done' | 'error'

function setStatus(s: Status): void {
  console.log('Status:', s);
}

Discussion

  • Be the first to comment on this lesson.