TypeScript Literal Types
A literal type is a type that accepts only one exact value, or a small set of exact values. The allowed values are written in the type itself.
Only the listed words fit
The direction variable can hold up or down. The assignment uses one of the listed values.
let direction: "up" | "down" = "up";
console.log(direction);An unlisted word is refused
The word left is not part of the type. The assignment fails at compile time.
let direction: "up" | "down" = "up";
direction = "left";A literal union as a parameter
The parameter accepts only the three listed colors. Each call passes one allowed word and logs an action.
function respond(light: "red" | "yellow" | "green") {
if (light === "red") {
console.log("Stop");
} else if (light === "yellow") {
console.log("Slow down");
} else {
console.log("Go");
}
}
respond("red");
respond("green");Example
function setLevel(level: "low" | "medium" | "high") {
if (level === "low") {
console.log("Volume 10");
} else if (level === "medium") {
console.log("Volume 20");
} else {
console.log("Volume 30");
}
}
setLevel("low");
setLevel("high");Key points
- A literal type accepts only the exact values it names.
- Any other value assigned to a literal type raises a type error.
- A literal union works well for a small fixed set of choices.
- A string type accepts any text at all.
In this example, setLevel takes a literal union of three words. The low call logs Volume 10 from the first branch. The high call falls to the last branch and logs Volume 30.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
A variable has type "up" | "down". Which assignment compiles?