TypeScript Literal Types
🎯 TypeScript Literal Types (Beginner → Advanced)
Literal Types in TypeScript let you restrict a variable to exact values instead of broad types like string or number.
They are extremely useful for APIs, UI states, configuration objects, and interviews.
1️⃣ What Are Literal Types?
A literal type represents one specific value.
Here, "success" is a string literal type.
2️⃣ Types of Literal Types ⭐
TypeScript supports these literal types:
String Literal Types
Number Literal Types
Boolean Literal Types
3️⃣ String Literal Types ⭐
✔ Very common in UI logic & APIs
4️⃣ Number Literal Types ⭐
✔ Useful for fixed numeric ranges
5️⃣ Boolean Literal Types ⭐
✔ Mostly used internally in advanced typing
6️⃣ Literal Types with const ⭐ (Very Important)
✔ const preserves the literal value
✔ let widens to string
7️⃣ Literal Types in Functions ⭐
✔ Prevents invalid arguments
8️⃣ Discriminated Unions (Best Use Case) ⭐⭐
✔ Safe
✔ Clean
✔ Interview favorite
9️⃣ Literal Types with Objects (as const) ⭐⭐
Inferred as:
✔ Freezes values at type level
🔟 Literal Types vs Enums ⭐
| Literal Types | Enums |
|---|---|
| No JS output | JS code generated |
| Lightweight | Heavier |
| Tree-shakeable | Not always |
| Preferred in modern TS | Legacy use |
✔ Literal types are often better than enums
1️⃣1️⃣ Common Mistakes ❌
Forgetting
constOver-widening types
Using enums unnecessarily
Not using unions with literals
Confusing literal vs primitive type
📌 Interview Questions (Must Prepare)
What are literal types?
Difference between
stringand"string"?Why use
as const?Literal types vs enums?
What is a discriminated union?
🔥 Real-World Use Cases
UI state management
Redux actions
API responses
Configuration objects
Form validation
✅ Summary
✔ Literal types restrict values to exact constants
✔ Used with union types for safety
✔ const preserves literal inference
✔ as const locks objects & arrays
✔ Power discriminated unions
✔ Essential for robust TypeScript code
