Last Updated : 21 Jan, 2025
TypeScript's literal types allow developers to specify exact values for variables, function parameters, or properties, enhancing type safety by ensuring variables can only hold predefined values.
Here are the types of literal types in TypeScript:
1. String Literal TypesString literal types allow a variable to accept only a specific set of string values.
JavaScript
type Direction = "Up" | "Down" | "Left" | "Right";
let move: Direction;
move = "Up"; // Valid assignment
// move = "Forward"; // Error: Type '"Forward"' is not assignable to type 'Direction'.
move = "Up"; // No error2. Numeric Literal Types
move = "Forward"; // Compile-time error
Numeric literal types restrict a variable to a specific set of numeric values..
JavaScript
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
function rollDice(): DiceRoll {
return 4; // Valid return value
// return 7; // Error: Type '7' is not assignable to type 'DiceRoll'.
}
Output :
rollDice(); // Returns 4 without error3. Boolean Literal Types
rollDice(); // Returning 7 causes a compile-time error
Boolean literal types constrain a variable to the boolean values true or false.
JavaScript
type Success = true;
function operation(): Success {
return true; // Valid return value
// return false; // Error: Type 'false' is not assignable to type 'true'.
}
Output:
operation(); // Returns true without errorBest Practices for Using TypeScript Literal Types
operation(); // Returning false causes a compile-time error
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4