TypeScript Literal Types
A literal type restricts a value to one exact value, rather than a whole category like `string` or `number`. For example, the type `"yes"` only accepts the exact string "yes".
Literal types become especially powerful when combined with unions, letting you define a variable that can only be one of a specific small set of exact values, similar to a lightweight enum.
let direction: "up" | "down" | "left" | "right";String and number literals
You can write `let answer: "yes" | "no";` to restrict a variable to exactly those two string values, or use numeric literals like `1 | 2 | 3`.
Combining with unions
Literal unions are often used for things like status codes, directions, or modes, giving you autocomplete and compile-time safety without a full enum.
let direction: "up" | "down" | "left" | "right";
direction = "up";
console.log(direction);updirection can only ever be one of the four listed string literals.
function setVolume(level: 0 | 1 | 2 | 3) {
console.log(`Volume set to ${level}`);
}
setVolume(2);Volume set to 2The parameter is restricted to the exact numeric literals 0, 1, 2, or 3.
Key points
- A literal type accepts only one exact value.
- Literal types are often combined with unions for a small fixed set of options.
- They give better autocomplete than plain string or number types.
- Assigning any other value causes a compile-time error.
