Skip to main content
A literal type in TypeScript is a type that represents one exact, specific primitive value rather than a broader category of values. By specifying a literal type, the compiler restricts a variable to hold only that exact value, effectively narrowing the domain of a collective primitive type (such as string, number, or boolean) to a single instance. A literal type is a strict subtype of its corresponding primitive type.

Core Literal Types

TypeScript supports literal types for three primary primitives: strings, numbers, and booleans.

Type Inference and Widening

TypeScript’s type inference engine handles literal types differently depending on how a variable is declared. This behavior is governed by a concept called literal widening. When a variable is declared with let or var, the compiler assumes the value may change. Therefore, it widens the inferred type from the literal value to the underlying primitive type. When declared with const, the compiler guarantees the value cannot be reassigned, so it infers the exact literal type.

Template Literal Types

TypeScript allows the construction of new string literal types by interpolating existing string literal types using template literal syntax at the type level. When combined with unions, template literal types distribute over the union members to generate a cross-product of exact string literals.

The as const Assertion (Const Assertions)

To prevent literal widening in complex data structures like objects or arrays, TypeScript provides the as const assertion. Applying as const instructs the compiler to:
  1. Infer exact literal types for all properties or elements.
  2. Recursively apply the readonly modifier to all properties.
  3. Treat arrays as readonly tuples rather than mutable arrays of a widened type.
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More