Literal types allow variables, function parameters, and object properties to hold only specific values, improving type safety and preventing invalid assignments.
- Restrict values to predefined literals.
- Improve type safety and code reliability.
- Commonly used with union types to define valid values.
Note: Literal types are commonly combined with union types to define a fixed set of allowed values, such as "Admin" | "User" | "Guest".
Types of literal types
Here are the different types of literal types:

1. String Literal Types
String literal types allow a variable to accept only a specific set of string values.
type Direction = "Up" | "Down" | "Left" | "Right";
let move: Direction;
move = "Up";
// move = "Forward";
Output:
Up
Error: Type '"Forward"' is not assignable to type 'Direction'
- Direction accepts only "Up", "Down", "Left", or "Right".
- Assigning any other value results in a compile-time error.
2. Numeric Literal Types
Numeric literal types restrict a variable to a specific set of numeric values.
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
function rollDice(): DiceRoll {
return 4; // Valid
// return 7; Error
}
console.log(rollDice());
Output :
4
Error: Type '7' is not assignable to type 'DiceRoll'
- DiceRoll accepts only the numbers 1 through 6.
- Returning any other value causes a compile-time error.
3. Boolean Literal Types
Boolean literal types restrict a variable or return value to either true or false.. Using both (true | false) is equivalent to the boolean type.
type Success = true;
function operation(): Success {
return true; // Valid return value
// return false; // Error
}
console.log(operation());
Output:
true
Error: Type 'false' is not assignable to type 'Success'
- Success is restricted to the value true.
- Returning false results in a compile-time error.