Today! We’re going to continue TypeScript learning like you’re a smart 5-year-old who loves to build things and asks “why?” (which is the best thing ever).
& yes “why?” is my way of learning.
I've divided this into 20 Chapters. and will go one by one and each will be of 2 - 3 min. of read.
This is a Continuation. if you have not read the Previous chapter - Chapter 7
Next : Chapter 9
🧩 Chapter 8: Literal Types – "Exactly This"
(aka: “this one exact thing.”)
🍷 Imagine This:
You tell your friend:
“Bring me a juice.”
They bring Berries 🍇, Peach 🥭, or orange 🍊 because you did not specify which one to bring.
Now you say:
“Bring me exactly orange juice.”
Now there’s zero confusion.
🎯 What are Literal Types?
They let you specify exactly what value is allowed instead of just “any string” or “any number.”
🧪 Example:
let direction: "left" | "right" | "up" | "down";
direction = "left"; // ✅
direction = "jump"; // ❌ Error! Not allowed
This says:
“direction can only be one of these exact strings.”
🛠️ Real World Example
let diceRoll: 1 | 2 | 3 | 4 | 5 | 6;
diceRoll = 3; // ✅
diceRoll = 7; // ❌ Error!
Combined with type aliases:
type Theme = "light" | "dark";
let currentTheme: Theme = "light";
🚀 Why is this powerful?
- It helps enforce exact values in APIs, configurations, UI options, etc.
- Makes your app safer by restricting invalid values.
- Helps with auto-suggestions in your preffered IDE.
Read Previous Chapters
If you enjoyed this and want to master TypeScript and other technologies, follow the series and drop a like!🤝
I’m a passionate software developer sharing the cool things I discover, hoping they help you level up on your coding journey.
How i created my own State Management Library : Rethinking State Management in React — From a Dev, for Developers.