Codectionary / Developer documentation / TypeScript

Literal Types

Literal types narrow a type down to one specific, exact value rather than a general category - "success" instead of string, or 200 instead of number. They are most useful combined with union types, letting you precisely constrain a value to a specific set of allowed options, catching typos and invalid values at compile time.

Syntax

let value: "specific-string" | 42 | true;

Examples

String and Numeric Literal Unions

Restricting a value to an exact, known set of options.

type Direction = "up" | "down" | "left" | "right";
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;

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

move("up");     // OK
// move("north"); // Error - not one of the allowed literals

const Assertions

Using "as const" to infer the most specific literal type possible.

let a = "hello";       // inferred as: string (widened)
const b = "hello";     // inferred as: "hello" (literal, since const cannot be reassigned)

let config = {
  mode: "production"
} as const;
// config.mode is typed as the literal "production", not string
// config.mode = "development"; // Error - as const also makes properties readonly

Best practices

  • Use literal type unions instead of a general string/number type when a value only has a small, known set of valid options - it catches typos at compile time
  • Use as const on object/array literals to lock in their most specific literal types, especially useful for configuration objects
  • Combine literal types with discriminated unions for exhaustive, type-safe handling of different variant shapes
  • Prefer literal unions over TypeScript enums for simple cases - they compile to nothing extra and integrate more naturally with plain JavaScript

At a glance

Purpose
Static types for JavaScript
File extension
.ts ยท .tsx
Runs in
Compiled to JavaScript
Usually used with
JavaScript and its ecosystem

Specifications & further reading

Related TypeScript documentation