在 TypeScript 中,PartialPick 是两个常用的工具类型(Utility Types),用于更灵活地操作对象类型,尤其适用于 API 请求、表单处理、组件 Props 等场景。


Partial 的用法

  • 作用:将一个类型的所有属性变为可选(即添加 ?)。

  • 适用场景:更新操作(如 PATCH 请求),只需传入部分字段。

  • 源码实现:

    type Partial<T> = { [P in keyof T]?: T[P]; };
    
  • 示例:

    interface User {
      id: number;
      name: string;
      email: string;
    }
    
    type UpdateUserDto = Partial<User>;
    // 等价于:{ id?: number; name?: string; email?: string; }
    
    const update: UpdateUserDto = { name: "Alice" }; // ✅ 合法
    

Pick 的用法

  • 作用:从一个类型中挑选指定的属性,组成一个新类型。

  • 适用场景:API 返回时只暴露部分字段(如列表页仅需 idname),避免敏感信息泄露。

  • 源码实现:

    type Pick<T, K extends keyof T> = { [P in K]: T[P]; };
    
  • 示例:

    interface User {
      id: number;
      name: string;
      email: string;
      password: string;
    }
    
    type UserPreview = Pick<User, 'id' | 'name' | 'email'>;
    // 等价于:{ id: number; name: string; email: string; }
    
    const user: UserPreview = { id: 1, name: "Bob", email: "bob@example.com" }; // ✅ 合法
    // user.password; // ❌ 报错:类型中不包含 password
    

组合使用示例

结合 PartialPick 可实现更精细的类型控制:

// 创建时不需要 id,且 password 必填
type CreateUserDto = Omit<User, 'id'> & { password: string };

// 更新时排除 id,其他字段可选
type UpdateUserDto = Partial<Omit<User, 'id'>> & { id: number };

// 分页查询只允许筛选 name 和 email
type UserQueryParams = Partial<Pick<User, 'name' | 'email'>> & { page: number; pageSize: number };

关键区别总结

特性 Partial<T> Pick<T, K>
目的 所有属性变可选 只保留指定属性
属性数量 不变(但都可选) 减少(仅保留 K 中的属性)
典型用途 更新请求、表单草稿 列表展示、安全字段暴露

💡 提示:两者都只作用于第一层属性,嵌套对象内部不会递归处理。若需深层操作,可考虑使用第三方库如 ts-toolbelt 或自定义递归工具类型。

更多推荐