Numeric Literal Types Syntax
You'll learn how to lock variables to specific numeric values using numeric literal types.
What Are Numeric Literal Types?
Just like you learned with string literal types, TypeScript lets you create types that represent exact numeric values. Instead of allowing any number, you can restrict a variable to accept only specific numbers like 0, 1, 404, or 2024.
Think of it like a vending machine button: instead of accepting any input, button "C3" is precisely C3—not C2, not C4. Numeric literal types work the same way for numbers.
Basic Syntax
The syntax is straightforward—use the number itself as the type:
let zero: 0 = 0;
let statusOK: 200 = 200;
let notFound: 404 = 404;
// This works
let portNumber: 8080 = 8080;
// Type error: Type '3000' is not assignable to type '8080'
portNumber = 3000; // ❌
Practical Applications
Numeric literals become powerful when combined with unions to represent finite sets of valid numbers:
let httpStatus: 200 | 404 | 500;
httpStatus = 200; // ✓
httpStatus = 404; // ✓
httpStatus = 301; // ❌ Type error
You can also use them in function parameters:
function setVolume(level: 0 | 50 | 100) {
// Only three valid volume settings
}
setVolume(50); // ✓
setVolume(75); // ❌ Type error
Key Takeaway: Numeric literal types let you specify exact numbers as types (like 404 or 0), constraining variables to only those precise values and catching invalid assignments at compile time.