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.
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"
Different ways to Create a TypeScript Mapped Type Utility Type
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:
Table of Content
- Basic Mapped Type
- Making Properties Optional
- Creating Read-Only Types
- Transforming Property Types