Skip to content

Mapped 类型 in TypeScript

Transform existing 类型通过映射 over 它们的键 使用自定义 modifiers and 筛选.

你将学到

  • 如何 mapped 类型 iterate over 键使用 [K in keyof T]
  • 添加 and 移除 readonly and 可选 modifiers 使用 + and -
  • 筛选键 使用 conditional 类型内部 mapped 类型
  • 如何构建-in utility 类型是 implemented as mapped 类型

概念讲解

The Mapping Syntax

A mapped type transforms an existing type by iterating over its keys. The syntax is { [K in keyof T]: NewType }, which creates a new type with the same keys as T but with each property's type replaced by NewType. For example, 类型 Stringify<T> = { [K in keyof T]: 字符串 } turns every property of T into a string. The K in keyof T part is the mapping — it loops over each key of T.

Modifiers: + and -

You can add or remove the readonly and ? (optional) modifiers in a mapped type. Adding is the default: { [K in keyof T]?: T[K] } makes all properties optional (this is how 部分<T> is implemented). Removing uses the - prefix: { [K in keyof T]-?: T[K] } removes optionality (this is 必需<T>). Similarly, -readonly removes readonly. This modifier manipulation is the foundation of many utility types.

Filtering Keys

You can filter which keys to include by adding a conditional type in the value position. If the condition is 从不, that key is excluded. For example, 类型 StringKeys<T> = { [K in keyof T]: T[K] extends 字符串 ? K : 从不 }[keyof T] extracts only the keys whose values are strings. This pattern, combined with 选取, lets you create types that select properties by their value type — a powerful technique for advanced type design.

示例代码

              // Basic mapped type — make every property a string.
type Stringify<T> = { [K in keyof T]: string };

interface User {
  id: number;
  name: string;
  isActive: boolean;
}

type StringUser = Stringify<User>;
// { id: string; name: string; isActive: string }

// Make all properties optional (this is how Partial<T> works).
type MyPartial<T> = { [K in keyof T]?: T[K] };

// Remove readonly (this is how Mutable<T> would work).
type Mutable<T> = { -readonly [K in keyof T]: T[K] };

// Make all properties readonly (this is how Readonly<T> works).
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };

// Filter keys by value type — get only string-valued keys.
type StringKeyNames<T> = {
  [K in keyof T]: T[K] extends string ? K : never;
}[keyof T];

type StringFields = StringKeyNames<User>; // "name"

const partial: MyPartial<User> = { name: "Alice" };
const readonlyUser: MyReadonly<User> = { id: 1, name: "Bob", isActive: true };
console.log(partial, readonlyUser, StringFields);
            

Mapped 类型循环 over 键使用 [K in keyof T]. Use + and - 到添加 or 移除 readonly/可选 modifiers. Conditional 类型 in 值位置筛选哪个键 是包含.

动手试一试

  • JSON 到 TypeScript

    Mapped 类型 transform generated 基础类型 for 特定 use 情况.

  • Code Diff

    Compare hand-编写类型使用 mapped-类型-derived equivalents.

常见错误

错误写法

Confusing mapped 类型使用索引 signatures

正确做法

Mapped 类型 [K in keyof T] iterate over known 键的 T. 索引 signatures { [键: 字符串]: V } 允许任何字符串键. 它们 look 相似但 behave very differently.

错误写法

Forgetting 那个 mapped 类型 preserve 键 names 但更改值 类型

正确做法

mapped 类型 { [K in keyof T]: NewType } keeps 相同键 as T 但 replaces 所有值 类型使用 NewType. 如果你 需要到 transform 值 selectively, 添加 conditional 类型.

练习 Mapped 类型 in TypeScript

4 个练习

练习 Mapped 类型 in TypeScript

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

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

查看错误