TExcelTAD
Home › TypeScript › TS Literal Types

TypeScript Literal Types

So far you have seen broad types like string and number, which accept any string or any number. A literal type is much narrower: it is a type with exactly one value. The type "left" only accepts the string "left"; the type 42 only accepts the number 42; true is a type containing only true.

On its own a single literal type isn't very useful, but combined in a union it becomes a precise "list of allowed values" — like an enum, but with zero runtime cost.

String, number and boolean literals

ts · try it yourself
type Direction = "up" | "down" | "left" | "right";
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;

function move(dir: Direction, steps: DiceRoll): string {
  return `Moving ${dir} by ${steps}`;
}

console.log(move("left", 3));
console.log(move("up", 6));
Moving left by 3
Moving up by 6

Passing anything outside the allowed set is caught by the compiler — including typos, which is the main win:

ts · try it yourself
type Direction = "up" | "down" | "left" | "right";

function move(dir: Direction): string {
  return `Moving ${dir}`;
}

console.log(move("rigth"));
main.ts(7,18): error TS2345: Argument of type '"rigth"' is not assignable to parameter of type 'Direction'.

Tip: Editors autocomplete literal unions, so after typing move(" you get a list of the four valid directions.

Literal inference: const vs let

TypeScript infers literal types differently depending on how a variable is declared. A const can never change, so its type is the literal itself. A let can be reassigned, so TypeScript widens the literal to its general type:

Declaration Inferred type
const a = "hello" "hello"
let b = "hello" string
const c = 3.5 3.5
let d = true boolean
const o = { mode: "dark" } { mode: string }

The last row surprises many people: properties of an object are mutable, so they are widened even when the object itself is const. This causes a classic error:

ts · try it yourself
type Theme = "light" | "dark";

function applyTheme(theme: Theme) {
  console.log("Theme set to", theme);
}

const settings = { theme: "dark" };
applyTheme(settings.theme);
main.ts(8,12): error TS2345: Argument of type 'string' is not assignable to parameter of type 'Theme'.

Fixing widening with as const

A const assertion (as const) tells TypeScript: "treat this value as deeply read-only and keep every literal". Objects become readonly with literal property types, and arrays become readonly tuples:

ts · try it yourself
type Theme = "light" | "dark";

function applyTheme(theme: Theme) {
  console.log("Theme set to", theme);
}

const settings = { theme: "dark" } as const;   // { readonly theme: "dark" }
applyTheme(settings.theme);

const sizes = ["S", "M", "L"] as const;         // readonly ["S", "M", "L"]
type Size = (typeof sizes)[number];             // "S" | "M" | "L"

function pick(size: Size) {
  return `You picked ${size}`;
}
console.log(pick(sizes[2]));
console.log(sizes.length);
Theme set to dark
You picked L
3

The pattern (typeof list)[number] is worth remembering: it turns a constant array into a union of its values, so you write the list once and get both the runtime array (for loops or dropdowns) and the type.

Other ways to avoid widening: annotate the variable (const settings: { theme: Theme } = ...), or use satisfies (covered in its own lesson).

Literal types as flags and options

Literal unions are perfect for function options, HTTP methods, log levels and similar fixed sets:

ts · try it yourself
type LogLevel = "debug" | "info" | "warn" | "error";
const order: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3 };

function makeLogger(minLevel: LogLevel) {
  return (level: LogLevel, msg: string) => {
    if (order[level] >= order[minLevel]) {
      console.log(`[${level.toUpperCase()}] ${msg}`);
    }
  };
}

const log = makeLogger("info");
log("debug", "cache size 12");   // filtered out
log("info", "server started");
log("error", "disk full");
[INFO] server started
[ERROR] disk full

Literal types vs enums

Literal union enum
Runtime code none (erased) generates an object
Usage "warn" LogLevel.Warn
Iterate values via as const array via Object.values
Works with plain JSON yes, values are just strings needs mapping for numeric enums

Many TypeScript teams prefer literal unions for their simplicity; enums are still fine, especially when you want a named namespace of constants.

Test yourself

What is the inferred type of let mode = "edit"?

  1. "edit"
  2. string
  3. readonly "edit"
  4. any

Given const xs = ["a", "b"] as const, what is (typeof xs)[number]?

  1. string
  2. string[]
  3. "a" | "b"
  4. number

Which value is assignable to the type 1 | 2 | 3?

  1. 0
  2. 2
  3. "2"
  4. 2.5