String, Number, and Combined Literals
Learn how to use literal types in TypeScript to define exact values. This module explains string literal types, number literal types, and combining literal types with practical examples.
1. String Literal Types
String literal types allow a variable to hold only a specific set of string values.
Basic Example
String literal types are useful for defining controlled values, such as configuration options or states.
2. Number Literal Types
Number literal types restrict a variable to specific numeric values.
Example
Number literal types are commonly used for API status codes or fixed numeric options.
3. Combining Literal Types
You can combine string and number literal types or union them with other types for greater flexibility.
Example
With Functions
Combining literal types ensures strict control over allowed values, reducing runtime errors.
Conclusion
Literal types in TypeScript provide precise control over variable values. String and number literals, combined with union types, enforce strict typing and make applications more predictable and safer for real-world development.