
Literal Types in TypeScript: Restricting Values Precisely
Create highly predictable and strict types
Catalog
Click on this table of contents to jump to the corresponding section
TypeScript's literal types allow developers to specify exact values for variables, function parameters, or properties, enhancing type safety by ensuring variables can only hold predefined values.
- Allow variables to have specific, exact values.
- Enhance code reliability by restricting permissible values.
Types of literal types
Here are the different types of literal types:
1. String Literal Types
String literal types allow a variable to accept only a specific set of string values.
Output:
In this example:
- The Direction type can only be one of the specified string literals: "Up", "Down", "Left", or "Right".
- Assigning any value outside this set results in a compile-time error.
2. Numeric Literal Types
Numeric literal types restrict a variable to a specific set of numeric values.
Output:
In this example:
- The DiceRoll type allows only the numbers 1 through 6.
- Returning a number outside this range causes a compile-time error.
3. Boolean Literal Types
Boolean literal types constrain a variable to the boolean values true or false.
Output:
In this example:
- The Success type is strictly true.
- Returning false would result in a compile-time error.
Lily and 4 people like this
Prev Post
Space The Final Frontier
Next Post
Telescopes 101
0 Comments
Leave a Reply
Recent Post

SMOTE for Imbalanced Classification with Python
12:28:00 16/05/2026

CLAHE Histogram Equalization with OpenCV: A Python Guide
12:06:00 16/05/2026

Histogram Equalization in Digital Image Processing
10:56:00 16/05/2026

Gaussian Noise Explained: What It Is and How It Works
10:36:00 16/05/2026

Python Image Blurring with OpenCV: Gaussian, Median & Bilateral Filter Guide
09:59:00 16/05/2026
Related Topics
Feeds
Don't miss what's next 👋
Enjoyed this content? Leave your email to get notified when we publish new insights, tutorials, and updates — no spam, ever.

