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