Pick with String Literal Unions
What you'll learn: How to use Pick with union types of property keys to extract multiple properties at once.
In the previous lesson, you learned that Pick<T, K> can select a subset of properties from a type. But what if you need to pick several properties? You don't need to call Pick multiple times—you can pass a union of string literals as the second type parameter.
The Core Idea
Instead of picking one property at a time, you can combine multiple property names into a single union type:
type User = {
id: number;
username: string;
email: string;
password: string;
createdAt: Date;
};
// Pick multiple properties at once
type PublicUser = Pick<User, "id" | "username">;
// Result:
// {
// id: number;
// username: string;
// }
The union "id" | "username" tells Pick to extract both properties in one go.
Why This Matters
Think of it like checking items off a grocery list. Instead of making separate trips to pick up apples, then bread, then milk, you grab all three in one pass. Similarly, Pick with a union grabs all the properties you specify in a single operation.
This pattern is especially useful when defining API responses, public-facing data shapes, or form subsets where you need consistent groupings of fields.
type LoginCredentials = Pick<User, "username" | "password">;
type UserProfile = Pick<User, "id" | "username" | "email" | "createdAt">;
Key Takeaway: Use Pick<T, K> with union types like "prop1" | "prop2" | "prop3" to extract multiple properties at once, creating focused type subsets efficiently.