Skip to main content

Literal Types

Literal types restrict a value to a specific primitive — a particular string, number, boolean, or bigint.

1function acceptsTwo(value: 2) { /* ... */ }2
3acceptsTwo(2);   // Works!4acceptsTwo(3);   // Error!incompatible-typeCannot call acceptsTwo with 3 bound to value because number literal 3 [1] is incompatible with number literal 2 [2].

Literal types support booleans (true, false), numbers (42, 3.14), strings ("foo"), and bigints (42n). They are commonly combined with union types:

1function getColor(name: "success" | "warning" | "danger") {2  switch (name) {3    case "success" : return "green";4    case "warning" : return "yellow";5    case "danger"  : return "red";6  }7}8
9getColor("success"); // Works!10getColor("danger");  // Works!11
12getColor("error");   // Error!incompatible-typeCannot call getColor with "error" bound to name because string literal error [1] is incompatible with union type [2].

When to use this

Use literal types when you need to restrict a value to specific constants rather than a broad type like string or number. They are especially useful in unions to define a fixed set of allowed values (e.g. "success" | "error"). For a more structured alternative to unions of literals, consider Flow Enums.

See Also

  • Primitive Types — the base types (number, string, etc.) that literals specialize
  • Unions — commonly used with literals to define finite sets of values
  • Flow Enums — a structured alternative to unions of literal types