Start Coding

Topics

Mapped Types in TypeScript

Mapped types are a powerful feature in TypeScript that allow you to create new types based on existing ones. They provide a way to transform properties of an existing type, creating a new type with modified characteristics.

Understanding Mapped Types

At its core, a mapped type is a generic type which uses a union of PropertyKeys (frequently created via a keyof operator) to iterate through keys and create a new type.

Basic Syntax

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

This syntax creates a new type by iterating over each property (P) in the original type (T).

Common Use Cases

1. Making all properties optional

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

2. Making all properties readonly

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

Advanced Features

Mapped types can be combined with other TypeScript features for more complex transformations:

Using conditional types

type NonNullable<T> = {
    [P in keyof T]: T[P] extends null | undefined ? never : T[P];
}

This example uses conditional types to remove null and undefined from property types.

Best Practices

  • Use mapped types to avoid repetition in type definitions
  • Combine with utility types for powerful type transformations
  • Be cautious with complex mapped types, as they can impact compilation performance

Conclusion

Mapped types are a cornerstone of TypeScript's type system, enabling developers to create flexible and reusable type transformations. By mastering mapped types, you can write more maintainable and type-safe code.

For more advanced type manipulations, explore conditional types and utility types in TypeScript.