TypeScript Pick<T, K> Utility Type Explained
Learn how Pick<T, K> creates a type by selecting specific properties from another type. Practical examples for creating subsets, DTOs, and component props.
Object Types
Detailed Explanation
Understanding Pick<T, K>
Pick<T, K> constructs a type by picking the set of properties whose keys are in the union K from type T. It is the type-level equivalent of selecting specific columns from a database table.
Syntax
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
Basic Example
interface User {
id: number;
name: string;
email: string;
password: string;
avatar: string;
createdAt: Date;
}
type UserPreview = Pick<User, "id" | "name" | "avatar">;
// Equivalent to:
// {
// id: number;
// name: string;
// avatar: string;
// }
Practical Pattern: API Response Shaping
// Full database model
interface Product {
id: string;
name: string;
price: number;
cost: number;
inventory: number;
supplier: string;
internalNotes: string;
}
// Public API response -- excludes internal fields
type PublicProduct = Pick<Product, "id" | "name" | "price">;
// Admin API response -- includes inventory
type AdminProduct = Pick<Product, "id" | "name" | "price" | "inventory" | "supplier">;
Pick vs Omit
Pick and Omit are complementary:
- Use Pick when you want a small subset from a large type (include-list)
- Use Omit when you want most properties except a few (exclude-list)
// These produce the same result:
type A = Pick<User, "id" | "name">;
type B = Omit<User, "email" | "password" | "avatar" | "createdAt">;
Use Case
Use Pick<T, K> when creating DTOs (Data Transfer Objects), shaping API responses, defining component props that use only some fields from a larger model, or building read-only views of data.