TypeScript Mapped Types
🔁 TypeScript Mapped Types (Beginner → Advanced)
Mapped Types in TypeScript allow you to create new types by transforming existing types.
They are a core building block of TypeScript’s type system and power many built-in utility types like Partial, Readonly, Pick, etc.
1️⃣ What Are Mapped Types?
A mapped type iterates over the keys of an existing type and creates a new type.
Think of it as a for loop for types.
2️⃣ Basic Syntax ⭐
keyof T→ gets all property keysK→ each keyT[K]→ type of that property
3️⃣ Simple Mapped Type Example
✔ CopyUser is exactly the same as User
4️⃣ Making All Properties Optional (Partial) ⭐
Equivalent to:
✔ Very common in forms & updates
5️⃣ Making All Properties Required (Required) ⭐
-?removes optional modifier
6️⃣ Making Properties Readonly (Readonly) ⭐
✔ Prevents accidental mutation
7️⃣ Removing readonly Modifier 🔥
✔ Useful when working with immutable libraries
8️⃣ Renaming Keys with as (Key Remapping) ⭐⭐
Result:
✔ Advanced & powerful
✔ Common in framework internals
9️⃣ Filtering Keys Using Mapped Types ⭐⭐
✔ Uses never to remove keys
🔟 Mapped Types + Conditional Types ⭐⭐⭐
✔ Very common in API responses
1️⃣1️⃣ Built-in Utility Types (Mapped Types in Action) ⭐⭐⭐
| Utility Type | What it does |
|---|---|
Partial<T> | Makes all properties optional |
Required<T> | Makes all properties required |
Readonly<T> | Makes all properties readonly |
Pick<T, K> | Select specific keys |
Omit<T, K> | Remove specific keys |
Record<K, T> | Create key-value map |
Example
1️⃣2️⃣ Record – Special Mapped Type
✔ Extremely common in configs
1️⃣3️⃣ Common Mistakes ❌
Forgetting
keyofOvercomplicating mapped types
Confusing mapped types with interfaces
Not using built-in utility types
Forgetting
-?or-readonly
📌 Interview Questions (Must Prepare)
What is a mapped type?
How does
keyofwork?Difference between
PartialandReadonlyHow to remove
readonlyor?How does key remapping work?
Difference between mapped types and interfaces
✅ Summary
✔ Mapped types transform existing types
✔ Built using keyof and index access
✔ Power most utility types
✔ Can add/remove ? and readonly
✔ Support key renaming & filtering
✔ Essential for advanced TypeScript & interviews
