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.
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"
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