0
0
Typescriptprogramming~3 mins

Why mapped types are needed in Typescript - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if you could change every property in a type with just one simple rule?

The Scenario

Imagine you have a list of user settings, and you want to create a new version where every setting is optional or read-only. Doing this by hand means writing out each property again and again.

The Problem

Manually rewriting each property is slow and boring. It's easy to make mistakes, like forgetting a property or mixing up types. When your settings grow or change, you must update many places, which wastes time and causes bugs.

The Solution

Mapped types let you create new types by transforming existing ones automatically. You write the rule once, and TypeScript applies it to every property. This saves time, reduces errors, and keeps your code clean and easy to update.

Before vs After
Before
type UserSettingsOptional = {
  theme?: string;
  notifications?: boolean;
  layout?: string;
};
After
type UserSettingsOptional<T> = {
  [K in keyof T]?: T[K];
};
What It Enables

Mapped types make it easy to create flexible, reusable types that adapt automatically as your data changes.

Real Life Example

When building a form, you can quickly create a version of your data where all fields are optional for partial updates, without rewriting every field manually.

Key Takeaways

Manual type changes are slow and error-prone.

Mapped types automate changes across all properties.

This leads to cleaner, safer, and easier-to-maintain code.