TypeScript – Literal Types Explained with Syntax & Real-World Examples
Introduction – What Are Literal Types in TypeScript?
TypeScript’s literal types allow you to specify exact values a variable can hold, rather than just a general type like string or number. This enables stricter type-checking, improved code precision, and safer logic validation—making your codebase easier to reason about and maintain.
In this guide, you’ll learn:
- What literal types are and how they work
- Different types of literal values: string, number, boolean
- How to use union with literal types
- Real-world examples and best practices
What Are Literal Types?
Literal types in TypeScript let you define a variable that can hold only a specific value, instead of just a general type.
Example:
let direction: "left" | "right" = "left";
Explanation:
directionis restricted to either"left"or"right".- Assigning anything else like
"up"will cause a compile-time error.
1. String Literal Types
Used when a variable must hold one or more specific string values.
Example:
type Theme = "light" | "dark";
let currentTheme: Theme = "light"; //
currentTheme = "dark"; //
// currentTheme = "blue"; // Error
Explanation:
- The
Themetype is a union of two string literals. - TypeScript restricts values to only
"light"or"dark".
2. Number Literal Types
Restrict a variable to hold only specific numeric values.
Example:
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
let roll: DiceRoll = 3; //
// roll = 7; // Error
Explanation:
- Useful in cases like dice games, configuration flags, or specific enums.
- Helps catch invalid values early.
3. Boolean Literal Types
Limit a value to exactly true or false.
Example:
let isProduction: true = true;
// isProduction = false; // Error
Explanation:
- While
booleanallows bothtrueandfalse, literal typing can force the value to stay fixed.
4. Combining Literal Types with Union Types
Unions are powerful with literals—they let you define a variable that accepts only a set of known values.
Example:
type TrafficSignal = "red" | "yellow" | "green";
function getSignalAction(signal: TrafficSignal): string {
if (signal === "red") return "Stop";
if (signal === "yellow") return "Slow down";
return "Go";
}
console.log(getSignalAction("green")); // "Go"
Explanation:
- Enforces safe values at compile time.
- Prevents accidental misspellings like
"gren".
5. Literal Inference with const
When you declare a variable with const, TypeScript infers literal types.
Example:
const role = "admin"; // inferred as "admin"
let status = "active"; // inferred as string
const variables retain the exact value as a literal type
let variables are inferred as a wider type like string
6. Using Literal Types in Function Parameters
Example:
function setLogLevel(level: "debug" | "info" | "error") {
console.log(`Log level set to ${level}`);
}
setLogLevel("debug"); //
// setLogLevel("warn"); // Error
Explanation:
- Great for controlling function inputs and creating self-documenting APIs.
- Errors are caught at development time, not runtime.
Common Mistakes & How to Avoid Them
| Mistake | Fix / Reason |
|---|---|
Using let instead of const | Use const to preserve literal type during inference |
| Forgetting union for multiple values | Use ` |
| Assigning invalid string/number | Let TS check for literal match at compile time |
Best Practices for Literal Types
- Use
constfor literal value preservation - Use
typealiases for common unions (liketype Status = "pending" | "complete") - Combine with enums or discriminated unions for advanced type safety
- Avoid mixing literal and wide types unless explicitly intended
Summary – Recap & Next Steps
Literal types add precision and safety to your TypeScript code by restricting values to known, specific constants. They’re invaluable in API design, enums, settings, and state management.
Key Takeaways:
- Literal types are exact-value types:
"left",1,true, etc. - Combine with union types to define strict valid values
- TypeScript uses literal inference automatically with
const - Prevents bugs from unexpected or invalid values
Real-world relevance: Literal types power config-driven systems, form validation, action types in Redux, traffic light logic, and more.
FAQs – Literal Types in TypeScript
Can I use literal types with numbers and booleans?
Yes! You can create literal types with true, false, or specific numbers like 1 | 2.
What happens if I use let instead of const?
TypeScript widens the type. For example, let theme = "light" becomes string, not "light".
Are literal types the same as enums?
No. Enums are runtime constructs; literal types exist only at compile time.
Can I create a type from specific values?
Yes, use union types like:
type Size = "small" | "medium" | "large";
Share Now :
