Skip to content

Mapped 类型

一句话解释

mapped 类型是 TypeScript construct 那个 iterates over 属性的 existing 类型 and produces 新类型使用 transformed 属性.

用大白话说

mapped 类型 iterates over 键的 existing 类型 and transforms 每个属性. 语法是 { [K in keyof T]: NewType }. It is the foundation of all utility types like Partial, Readonly, and Pick.

For example, 类型 Stringify<T> = { [K in keyof T]: 字符串 } takes any type T and creates a new type with the same keys but all values as strings.

Mapped types are powerful for creating type transformations: making properties optional, readonly, or changing their types. The built-in utility types (Partial, Required, Readonly, Pick, Omit) are all mapped types.

示例

typescript
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type Getters<T> = { [K in keyof T]: () => T[K] };

可变移除 readonly modifiers. Getters 创建 getter 函数 for 每个属性.

相关术语

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表