0
0
Typescriptprogramming~3 mins

Why Mapped type with conditional types in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how one simple rule can replace dozens of repetitive type changes!

The Scenario

Imagine you have a big list of properties in an object, and you want to change the type of some properties based on certain rules. Doing this by hand means writing many lines of code for each property, checking conditions one by one.

The Problem

Manually updating each property is slow and easy to mess up. If the object changes, you must rewrite or copy-paste code again. It's hard to keep track and fix mistakes, especially when the rules are complex.

The Solution

Mapped types with conditional types let you write one smart rule that automatically changes property types based on conditions. This saves time, reduces errors, and keeps your code clean and easy to update.

Before vs After
Before
type Manual = {
  name: string;
  age: number | null;
  active: boolean;
};
After
type Conditional<T> = {
  [K in keyof T]: T[K] extends number ? string : T[K];
};
What It Enables

You can create flexible, reusable types that adapt automatically to your data's shape and rules.

Real Life Example

When building a form, you might want to convert all number fields to strings for input handling, but keep other fields unchanged. Mapped types with conditional types do this in one simple step.

Key Takeaways

Manual property updates are slow and error-prone.

Mapped types with conditional types automate type changes based on rules.

This makes your code cleaner, safer, and easier to maintain.