TypeScript ยท Chapter 14 of 44

TypeScript Literal Types

A literal type restricts a value to one exact value, rather than a whole category like `string` or `number`. For example, the type `"yes"` only accepts the exact string "yes".

Literal types become especially powerful when combined with unions, letting you define a variable that can only be one of a specific small set of exact values, similar to a lightweight enum.

Syntax
let direction: "up" | "down" | "left" | "right";

String and number literals

You can write `let answer: "yes" | "no";` to restrict a variable to exactly those two string values, or use numeric literals like `1 | 2 | 3`.

Combining with unions

Literal unions are often used for things like status codes, directions, or modes, giving you autocomplete and compile-time safety without a full enum.

Example 1 (typescript)
let direction: "up" | "down" | "left" | "right";
direction = "up";
console.log(direction);
Output
up

direction can only ever be one of the four listed string literals.

Example 2 (typescript)
function setVolume(level: 0 | 1 | 2 | 3) {
  console.log(`Volume set to ${level}`);
}
setVolume(2);
Output
Volume set to 2

The parameter is restricted to the exact numeric literals 0, 1, 2, or 3.

Key points

  • A literal type accepts only one exact value.
  • Literal types are often combined with unions for a small fixed set of options.
  • They give better autocomplete than plain string or number types.
  • Assigning any other value causes a compile-time error.
๐Ÿ’ก Note: Literal type unions are a lightweight, popular alternative to enums in modern TypeScript.

๐Ÿ“ Quick Quiz

1. What does the literal type "yes" accept?

2. How are literal types often combined for more flexibility?

3. What is a common use for literal type unions?