乐闻世界logo
搜索文章和话题

How do you use "Mapped Types" in TypeScript?

1个答案

1

Mapped types in TypeScript are a powerful feature that allows us to derive a new type from an existing one, where each property can be transformed in a specific manner. Mapped types help maintain consistency between types while reducing code duplication and improving development efficiency.

Basic Usage of Mapped Types

Mapped types are typically used in conjunction with index signatures. The basic form is as follows:

typescript
type Keys = 'option1' | 'option2' | 'option3'; type Flags = { [K in Keys]: boolean };

In this example, Keys is a union type with three possible values, and Flags is a mapped type that maps each key from Keys to a boolean type. Therefore, the structure of Flags is equivalent to:

typescript
type Flags = { option1: boolean; option2: boolean; option3: boolean; };

Application Example: Conditional Mapping

Mapped types can be combined with TypeScript's conditional types to achieve more complex type transformations. For example, we can create a mapped type that determines the new type of each property based on the value type of the original type:

typescript
type Options = { width: number; height: number; label: string; }; type NullableOptions = { [K in keyof Options]?: Options[K]; };

In this example, each property of NullableOptions is optional and has the same type as the corresponding property in Options.

Use Case: Creating a New Type from an Existing Type

Suppose we need to generate a new type based on an existing one where each property is read-only. This can be achieved using mapped types:

typescript
type User = { name: string; age: number; }; type ReadOnlyUser = { readonly [K in keyof User]: User[K]; };

In this example, ReadOnlyUser is a new type derived from User, where each property is marked with the readonly modifier. This means that once an object of type ReadOnlyUser is created, its properties cannot be modified.

Summary

Mapped types are a highly flexible tool in TypeScript that helps developers efficiently manipulate and transform type information while maintaining type safety. The examples above demonstrate how to use mapped types for type creation and transformation, and they can be flexibly adapted and extended according to specific requirements in actual development. Additionally, by combining with advanced features such as generics and conditional types, the power of mapped types becomes even more significant.

2024年8月2日 13:54 回复

你的答案