Literal Types in Function Parameters
You'll learn how to use literal types to lock down function parameters to exact, pre-approved values.
The Core Idea
Sometimes you don't just want a function to accept any string or number—you want it to accept specific strings or numbers. Literal types let you define parameters that only accept exact values like "left", "right", or 42. This prevents invalid arguments at compile time.
Think of it like a vending machine that only accepts specific coins: quarters, dimes, and nickels. You can't just throw any object in there. Similarly, literal types ensure callers can only pass approved values.
Basic Syntax
function setAlignment(align: "left" | "center" | "right") {
console.log(`Aligning to ${align}`);
}
setAlignment("left"); // ✓ Valid
setAlignment("center"); // ✓ Valid
setAlignment("top"); // ✗ Error: Argument of type '"top"' is not assignable
The parameter align only accepts those three specific strings—nothing else.
With Numeric Literals
function setVolume(level: 0 | 1 | 2 | 3) {
console.log(`Volume set to ${level}`);
}
setVolume(2); // ✓ Valid
setVolume(5); // ✗ Error: Argument of type '5' is not assignable
Multiple Parameters with Literals
function move(direction: "up" | "down" | "left" | "right", speed: 1 | 2 | 3) {
console.log(`Moving ${direction} at speed ${speed}`);
}
move("up", 2); // ✓ Valid
move("diagonal", 1); // ✗ Error: "diagonal" not allowed
Each parameter has its own set of allowed literal values.
Key Takeaway: Literal types in function parameters restrict arguments to exact, predefined values, catching invalid inputs at compile time and serving as inline documentation for valid options.