0
0
Typescriptprogramming~7 mins

Mapped type for deep transformations in Typescript

Choose your learning style9 modes available
Introduction

Mapped types let you change the shape of an object type. Deep transformations help you change nested objects step-by-step.

You want to make all properties in a nested object optional.
You need to convert all string properties in a nested object to numbers.
You want to apply a rule to every nested level of an object type.
You want to create a readonly version of a deeply nested object.
Syntax
Typescript
type DeepTransform<T> = {
  [K in keyof T]: T[K] extends object ? DeepTransform<T[K]> : /* transformation */ T[K]
}

The syntax uses [K in keyof T] to loop over keys.

Use conditional types to check if a property is an object and apply recursion.

Examples
This makes every property and nested property readonly.
Typescript
type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K]
};
This makes every property and nested property optional.
Typescript
type DeepPartial<T> = {
  [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K]
};
This converts all string properties to number, even nested ones.
Typescript
type DeepStringToNumber<T> = {
  [K in keyof T]: T[K] extends string ? number : T[K] extends object ? DeepStringToNumber<T[K]> : T[K]
};
Sample Program

This program creates a deeply readonly User type. Trying to change any property causes an error. The console logs show the values.

Typescript
type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K]
};

interface User {
  name: string;
  address: {
    street: string;
    city: string;
  };
}

const user: DeepReadonly<User> = {
  name: "Alice",
  address: {
    street: "123 Main St",
    city: "Wonderland"
  }
};

// user.name = "Bob"; // Error: cannot assign to readonly property
// user.address.city = "Elsewhere"; // Error: cannot assign to readonly property

console.log(user.name);
console.log(user.address.city);
OutputSuccess
Important Notes

Deep transformations use recursion in types to handle nested objects.

Be careful with types like arrays or functions; you might need extra checks.

Mapped types do not change runtime behavior, only type checking.

Summary

Mapped types let you change object types key by key.

Deep transformations apply changes to nested objects recursively.

Use conditional types to decide when to recurse or transform.