How to work with mapped types in TypeScript



Image not found!!

Mapped types in TypeScript allow you to create new types by transforming the properties of an existing type. This can be useful for tasks like making properties read-only, optional, or even creating a new type based on the keys of an existing type. Here's a brief overview of how to work with mapped types in TypeScript:

Basic Mapped Type Syntax

The basic syntax for a mapped type looks like this:

typescript
type MappedType<T> = { [K in keyof T]: /* transform each property here */; };
  • T is the original type.
  • K is a key in the original type.
  • keyof T is a TypeScript utility type that represents all possible keys of T.
  • The part after in is the transformation applied to each property.

Readonly Mapped Type

For example, you can create a read-only version of an object type:

typescript
type ReadonlyType<T> = { readonly [K in keyof T]: T[K]; }; // Example usage type User = { name: string; age: number; }; type ReadonlyUser = ReadonlyType<User>; // ReadonlyUser: { readonly name: string; readonly age: number; }

Partial Mapped Type

Creating a partial version of a type:

typescript
type PartialType<T> = { [K in keyof T]?: T[K]; }; // Example usage type PartialUser = PartialType<User>; // PartialUser: { name?: string; age?: number; }

Pick Mapped Type

Selecting specific properties from a type:

typescript
type PickType<T, K extends keyof T> = { [P in K]: T[P]; }; // Example usage type PickedUser = PickType<User, 'name'>; // PickedUser: { name: string; }

Record Mapped Type

Creating a type with specified keys and a common value type:

typescript
type RecordType<K extends string | number | symbol, T> = { [P in K]: T; }; // Example usage type StringRecord = RecordType<'a' | 'b' | 'c', string>; // StringRecord: { a: string; b: string; c: string; }

Conditional Mapped Type

Applying a condition to include or exclude properties:

typescript
type FilterNumberProperties<T> = { [K in keyof T]: T[K] extends number ? T[K] : never; }; // Example usage type NumberProperties = FilterNumberProperties<User>; // NumberProperties: { age: number; }

Keyof and Lookup Types

Using keyof and lookup types to extract and use specific properties:

typescript
type UserKeys = keyof User; // UserKeys: "name" | "age" type AgeType = User["age"]; // AgeType: number

These are just a few examples, and there are many other ways to use mapped types in TypeScript. Mapped types provide powerful tools for creating new types based on existing ones, allowing for more flexible and reusable code.