0
0
Typescriptprogramming~3 mins

Why Mapped type for deep transformations in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could rename every nested property in your data with just one simple rule?

The Scenario

Imagine you have a big box of nested folders and files, and you want to rename every file inside every folder by hand.

Doing this manually means opening each folder, finding each file, and renaming it one by one.

The Problem

This manual way is slow and tiring.

You might miss some files or make mistakes.

It's hard to keep track of all changes, especially when folders are deeply nested.

The Solution

Mapped types for deep transformations let you tell TypeScript to automatically change every property inside an object, even if it's nested inside other objects.

This means you write one rule, and it applies everywhere, saving time and avoiding errors.

Before vs After
Before
type RenameProps<T> = { a: string; b: { c: number; d: boolean } };
// Manually rename each property
interface NewType {
  newA: string;
  b: {
    newC: number;
    newD: boolean;
  };
}
After
type RenameProps<T> = {
  [K in keyof T as `new${Capitalize<string & K>}`]: T[K] extends object ? RenameProps<T[K]> : T[K]
};
What It Enables

You can transform complex nested data structures automatically and safely with just one reusable type.

Real Life Example

When working with data from an API, you might want to convert all property names to a different style or prefix them for clarity.

Mapped types for deep transformations let you do this easily without rewriting types for every nested level.

Key Takeaways

Manual renaming of nested properties is slow and error-prone.

Mapped types automate deep transformations across all nested levels.

This saves time and keeps your code consistent and safe.