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 asDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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 withlet 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:
- Infer exact literal types for all properties or elements.
- Recursively apply the
readonlymodifier to all properties. - Treat arrays as
readonlytuples rather than mutable arrays of a widened type.
Master TypeScript with Deep Grasping Methodology!Learn More





