Utility types 是内置泛型,可以转换现有类型,因此您可以衍生新类型,而不是重新定义它们。它们保持类型的 DRY 原则并与其源保持同步。
ts
{ : ; : ; : ; : ; }
<>;
<>;
<>;
<, | >;
<, >;
Utility types 是内置泛型,可以转换现有类型,因此您可以衍生新类型,而不是重新定义它们。它们保持类型的 DRY 原则并与其源保持同步。
{ : ; : ; : ; : ; }
<>;
<>;
<>;
<, | >;
<, >;
// Update endpoint: accept any subset of fields
function update(id: number, changes: Partial<User>) { ... }
update(1, { name: "New" }); // ✅ only the fields you change
// Create endpoint: everything except the server-generated id
type CreateUser = Omit<User, "id">;
如果您向 User 添加字段,所有这些都会自动更新——无需担心遗漏第二个定义。
Record<string, number>; // { [key: string]: number } — dictionaries
ReturnType<typeof fn>; // the return type of a function
Parameters<typeof fn>; // tuple of a function's parameter types
NonNullable<string | null>; // string (strips null/undefined)
Extract<T, U>; Exclude<T, U>; // filter members of a union
Utility types 让您能够声明式地表达类型之间的关系("创建表单是去掉 id 的 user")。
它们减少重复,保持衍生类型与其源自动一致,并且在真实代码库中随处可见——特别是 Partial 用于更新,Omit/Pick 用于 DTOs,Record 用于映射。