Utility 类型 in TypeScript
构建-in 类型 transformations: 部分, 必需, 选取, Omit, 记录, Readonly, and 更多.
你将学到
- 如何部分<T> and 必需<T> 切换可选属性
- Using 选取<T, K> and Omit<T, K> 到选择 or 排除键
- 记录<K, V> for keyed 映射 and Readonly<T> for immutability
- ReturnType<T> and 参数<T> for 函数类型 extraction
概念讲解
Property Modifiers
部分<T> makes every property of T optional — useful for update/patch operations where you only send changed fields. 必需<T> does the opposite, making all properties required. Readonly<T> makes every property readonly, preventing mutation. These three are the most commonly used utility types and are built from mapped types internally.
Key Selection
选取<T, K> creates a new type with only the keys K from T. Omit<T, K> creates a type with all keys except K. These are invaluable for creating focused types from a large base type: 类型 UserSummary = 选取<用户, "id" | "name"> gives you a lightweight view with just ID and name, while 类型 UserUpdate = Omit<用户, "id" | "createdAt"> excludes fields that should not be edited.
Function and Record Types
记录<K, V> creates an object type with keys K and values V — cleaner than an index signature. ReturnType<T> extracts the return type of a function type, and 参数<T> extracts the parameter types as a tuple. These let you derive types from existing functions without duplicating their signatures, keeping your types in sync with your implementations automatically.
示例代码
interface User {
id: number;
name: string;
email: string;
role: string;
}
// Partial — all properties become optional (for updates).
type UserUpdate = Partial<User>;
const patch: UserUpdate = { name: "New Name" };
// Pick — select only specific keys.
type UserSummary = Pick<User, "id" | "name">;
const summary: UserSummary = { id: 1, name: "Alice" };
// Omit — exclude specific keys.
type CreateUser = Omit<User, "id">;
const newUser: CreateUser = { name: "Bob", email: "[email protected]", role: "user" };
// Record — typed map with known keys.
type Roles = Record<"admin" | "editor" | "viewer", number>;
const counts: Roles = { admin: 2, editor: 5, viewer: 100 };
// ReturnType — extract a function's return type.
function createUser() {
return { id: 1, name: "Alice" };
}
type CreatedUser = ReturnType<typeof createUser>;
console.log(patch, summary, newUser, counts);
部分/必需/Readonly 修改属性. 选取/Omit 选择键. 记录创建 keyed 映射. ReturnType/参数 extract 函数类型. 这些是 构建从 mapped and conditional 类型.
动手试一试
- JSON 到 TypeScript
Generated 基础类型能 是 refined 使用选取, Omit, and 部分.
- JSON Schema Validator
验证部分 or 选取 subsets 的你的数据 shapes.
常见错误
错误写法
Using 部分<T> for 创建操作哪里所有字段是 必需
正确做法
部分制作所有字段可选, 哪个是 错误 for creation. Use Omit<T, 'id'> 到排除仅 auto-generated 字段, keeping REST 必需.
错误写法
Re-declaring 类型相反的 using 选取 and Omit 到 derive 它们
正确做法
Derive focused 类型从 基础类型使用选取 and Omit. 这个 keeps 它们 in sync — 如果基础类型更改, derived 类型更新 automatically.
练习 Utility 类型 in TypeScript
16 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。