Open In App

Different ways to Create a TypeScript Mapped Type Utility Type

Last Updated : 10 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Mapped types in TypeScript are a powerful and flexible feature that allows developers to create new types by transforming existing ones. These types enable you to iterate through the keys of an object type and construct a new type based on the original type’s keys and values. This feature is particularly useful for creating utility types that can modify properties of an existing type in a DRY (Don’t Repeat Yourself) manner, enhancing code maintainability and type safety. Mapped types in TypeScript can be created using various techniques, each serving different purposes and use cases which are as follow:

Basic Mapped Type

A basic mapped type allows you to iterate over the keys of an existing type and apply a transformation to its properties.

Syntax:

type MappedType<T> = {
[P in keyof T]: T[P];
};

Example: Creating a simple mapped type that mirrors the original type. This example demonstrates a basic mapped type that creates a new type identical to the original Person type.

Javascript
type Person = {
    name: string;
    age: number;
};

type ReadOnlyPerson = {
    readonly [P in keyof Person]: Person[P];
};

function attemptToUpdatePerson(person: ReadOnlyPerson) {
    console.log(
        `Before update: Name - ${person.name}, 
            Age - ${person.age}`);
    
    // TypeScript will throw an error for the next lines, 
    // demonstrating immutability.
    // Uncommenting these lines will result in a 
    // compile-time error.
    // person.name = "Alice";
    // person.age = 35;
    
    console.log(
        `After attempted update: Name - ${person.name}, 
            Age - ${person.age}`);
}

const person: ReadOnlyPerson = {
    name: "Bob",
    age: 30
};

attemptToUpdatePerson(person);

Output:

"Before update: Name - Bob, Age - 30" 
"After attempted update: Name - Bob, Age - 30"

Making Properties Optional

Mapped types can be used to make all properties of a type optional, useful for creating types that allow partial object updates.

Syntax:

type PartialType<T> = {
[P in keyof T]?: T[P];
};

Example: Transforming a type to make all its properties optional. In this example, PartialType is a mapped type that makes every property of Person optional, demonstrating the utility of mapped types in modifying property optionality.

Javascript
type Person = {
    name: string;
    age: number;
};

type PartialPerson = {
    [P in keyof Person]?: Person[P];
};

function logPersonInfo(person: PartialPerson) {
    console.log(`Name: ${person.name}`);
    if (person.age !== undefined) {
    console.log(`Age: ${person.age}`);
    } else {
    console.log(`Age is not provided.`);
    }
}

const partialPerson: PartialPerson = {
    name: "Alice" // 'age' property is now optional
};

logPersonInfo(partialPerson);

Output

"Name: Alice" 
"Age is not provided."

Creating Read-Only Types

Mapped types can also enforce immutability by making all properties of a type read-only.

Syntax:

type ReadOnlyType<T> = {
readonly [P in keyof T]: T[P];
};

Example: Creating a read-only version of a type. This example illustrates how to create an immutable version of the Person type using mapped types, showcasing their ability to enforce property immutability.

Javascript
type Person = {
name: string,
age: number,
};

// Using TypeScript's built-in ReadOnly 
// utility type for simplicity
type ReadOnlyPerson = Readonly<Person>;

function displayPersonInfo(person: ReadOnlyPerson) {
console.log(`Name: ${person.name}, Age: ${person.age}`);
}

function attemptToModifyPerson(person: ReadOnlyPerson) {
console.log(
        `Attempting to modify a read-only person object...`);

// The following lines would cause TypeScript 
// to throw a compile-time error
// Uncommenting them will demonstrate the immutability
// enforced by the ReadOnlyPerson type.
// person.name = "Alice";
// person.age = 35;

displayPersonInfo(person);
}

const person: ReadOnlyPerson = {
name: "Bob",
age: 30,
};

displayPersonInfo(person);
attemptToModifyPerson(person);

Output

"Name: Bob, Age: 30" 
"Attempting to modify a read-only person object..."
"Name: Bob, Age: 30"

Transforming Property Types

Mapped types can also transform the types of the properties of an existing type, allowing for comprehensive type manipulation.

Syntax:

type PropertyTypeTransform<T> = {
[P in keyof T]: T[P] extends infer R ? Transform<R> : never;
};

Example: Converting all string properties of a type to boolean flags. Here, StringToBoolean is a mapped type that transforms all string properties of the Person type into booleans.

Javascript
type User = {
    id: number;
    name: string;
    email: string;
    verified: boolean;
};

// Transform all string properties to boolean properties
type StringsToBooleans<T> = {
    [P in keyof T]: T[P] extends string ? boolean : T[P];
};

function transformStringsToBooleans<T>(user: T): 
    StringsToBooleans<T> {
    let result = {} as StringsToBooleans<T>;
    for (const key in user) {
        if (typeof user[key] === 'string') {
            result[key] = true; 
            
            // Transform string to boolean true for 
            // demonstration
        } else {
            result[key] = user[key];
        }
    }
    return result;
}

const user: User = {
    id: 1,
    name: "Alice",
    email: "alice@example.com",
    verified: false,
};

const transformedUser = 
        transformStringsToBooleans(user);
console.log(transformedUser);

Output

"Name: Bob, Age: 30" 
"Attempting to modify a read-only person object..."
"Name: Bob, Age: 30"

Mapping Property Types to Union Types

Mapped types can also be used to transform the types of properties into a union of specified types. This approach is particularly useful for scenarios where you want to create a type that accepts multiple types for each property.

Example: The TypeScript code defines NullableUser<T>, enabling properties of User type to be either their original type or null. The setNulls function initializes all properties to `null`.

JavaScript
type User = {
    id: number;
    name: string;
    email: string;
    verified: boolean;
};

// Map each property to a union type with null or the original type
type NullableUser<T> = {
    [P in keyof T]: T[P] | null;
};

function setNulls<T>(user: T): NullableUser<T> {
    let nullableUser = {} as NullableUser<T>;
    for (const key in user) {
        // Initialize all properties to null
        nullableUser[key] = null; 
    }
    return nullableUser;
}

const user: User = {
    id: 1,
    name: "Nikunj",
    email: "nikunjsonigara@gfg.com",
    verified: false,
};

const nullableUser = setNulls(user);
console.log(nullableUser);

Output:

{ id: null, name: null, email: null, verified: null }


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads