0
0
Typescriptprogramming~7 mins

Mapped type with conditional types in Typescript

Choose your learning style9 modes available
Introduction

Mapped types with conditional types help you create new object types by changing properties based on conditions. This makes your code flexible and safe.

When you want to create a new type by changing some properties of an existing type based on their types.
When you need to filter or transform properties in an object type depending on their value types.
When you want to enforce different rules for different properties in a type automatically.
When you want to build utility types that adapt to the shape of other types.
Syntax
Typescript
type NewType<T> = {
  [P in keyof T]: T[P] extends SomeCondition ? TypeIfTrue : TypeIfFalse
};

Mapped types loop over keys of a type using [P in keyof T].

Conditional types check each property type with extends and choose a type accordingly.

Examples
This applies the readonly modifier to property types only if the property type is string.
Typescript
type ReadonlyStrings<T> = {
  [P in keyof T]: T[P] extends string ? Readonly<T[P]> : T[P]
};
This adds null to properties that are numbers.
Typescript
type NullableNumbers<T> = {
  [P in keyof T]: T[P] extends number ? T[P] | null : T[P]
};
Sample Program

This program creates a new type where string properties can also be undefined. The name property is allowed to be undefined because it is a string in the original type.

Typescript
type User = {
  id: number;
  name: string;
  active: boolean;
};

type OptionalStrings<T> = {
  [P in keyof T]: T[P] extends string ? T[P] | undefined : T[P]
};

const user1: OptionalStrings<User> = {
  id: 1,
  name: undefined, // allowed because name is string type
  active: true
};

console.log(user1);
OutputSuccess
Important Notes

Conditional types run for each property separately inside the mapped type.

You can combine multiple conditions for more complex transformations.

Mapped types with conditional types help keep your types DRY and adaptable.

Summary

Mapped types loop over keys to create new types.

Conditional types choose types based on conditions.

Together, they let you transform object types smartly and safely.