Literal type is a type that only allows a specific literal value.

Literal types are common in type systems that can describe very precise values. They are often used with union types.

For example, in Typescript:

type Direction = "up" | "down" | "left" | "right"

Each string value is a literal type, and the union allows only those specific strings.

Literal types are useful for:

  • Modeling command names
  • Modeling states
  • Restricting configuration values
  • Replacing loosely checked strings with precise types

Anki

id: literal-type-definition deck: Computer Science::Data Types tags: data-types literal-type

Q: What is a literal type? A: A literal type is a type that only allows a specific literal value.

id: literal-type-union deck: Computer Science::Data Types tags: data-types literal-type union-type typescript

Q: How are literal types often used in TypeScript? A: They are often combined into union types, such as "up" | "down" | "left" | "right".