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:
The basic syntax for a mapped type looks like this:
typescripttype 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
.in
is the transformation applied to each property.For example, you can create a read-only version of an object type:
typescripttype 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; }
Creating a partial version of a type:
typescripttype PartialType<T> = {
[K in keyof T]?: T[K];
};
// Example usage
type PartialUser = PartialType<User>;
// PartialUser: { name?: string; age?: number; }
Selecting specific properties from a type:
typescripttype PickType<T, K extends keyof T> = {
[P in K]: T[P];
};
// Example usage
type PickedUser = PickType<User, 'name'>;
// PickedUser: { name: string; }
Creating a type with specified keys and a common value type:
typescripttype 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; }
Applying a condition to include or exclude properties:
typescripttype FilterNumberProperties<T> = {
[K in keyof T]: T[K] extends number ? T[K] : never;
};
// Example usage
type NumberProperties = FilterNumberProperties<User>;
// NumberProperties: { age: number; }
Using keyof
and lookup types to extract and use specific properties:
typescripttype 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.