0Pricing
TypeScript Academy · Lesson

String and Numeric Literal Types

Restrict values to exact strings and numbers with literal types.

What Is a Literal Type?

Most types describe a set of values. string means any string, number means any number. A literal type narrows this down to one exact value.

The type 'north' only allows the string 'north' — nothing else. Literal types let you model precise, finite sets of allowed values right in the type system.

let dir: 'north' = 'north';
console.log(dir);
// dir = 'south'; // Error: not assignable to type 'north'

String Literal Unions

A single literal isn't very useful alone. Combine several with | to form a union of literals. This is the idiomatic way to model a fixed set of options.

Direction below can only ever be one of four exact strings.

type Direction = 'north' | 'south' | 'east' | 'west';

let heading: Direction = 'east';
console.log('Heading:', heading);

heading = 'west';
console.log('Now:', heading);

All lessons in this course

  1. String and Numeric Literal Types
  2. Boolean Literals and Literal Inference
  3. const Assertions with as const
  4. Combining Literals into Unions
← Back to TypeScript Academy