Literal Type (TypeScript)

A literal type is a type that allows only one exact value, such as the string `"left"` or the number `42`. Combined with unions, literal types restrict a value to a small set of allowed options.

TypeScript

Instead of saying a value is any `string`, a literal type says it must be exactly `"on"` or exactly `"off"`. A union of literals (`"on" | "off"`) is a lightweight, type-safe alternative to an enum.

TypeScript widens literals to their base type when you use `let`, but a `const` keeps the precise literal type. This is why `const x = "on"` has type `"on"`, not `string`.

Examples

TypeScript — Compile error: Argument of type '"up"' is not assignable to parameter of type 'Direction'.

type Direction = "left" | "right";

function move(dir: Direction) {
  console.log("moving " + dir);
}

move("left");
move("up");

Learn it in a lesson

See also

Back to the Dictionary