Hint
Pick selects a subset of keys; Omit excludes specific keys — both create derived types from existing ones
Pick<T, K> — creates a type with only the specified keys from T:
interface User {
id: number;
name: string;
email: string;
password: string;
createdAt: Date;
}
// Only expose safe fields to the client
type PublicUser = Pick<User, 'id' | 'name' | 'email'>;
// { id: number; name: string; email: string }
// Safe to serialize and send over the wire
function getUserPublic(id: number): PublicUser {
const user = findUser(id);
return { id: user.id, name: user.name, email: user.email };
}
Omit<T, K> — creates a type with the specified keys removed:
// Remove sensitive fields
type SafeUser = Omit<User, 'password'>;
// Remove auto-managed fields for create inputs
type CreateUserInput = Omit<User, 'id' | 'createdAt'>;
// { name: string; email: string; password: string }
function createUser(input: CreateUserInput): User {
return { ...input, id: generateId(), createdAt: new Date() };
}
Pick vs Omit — when to choose:
Omit when the excluded set is small and stable. If you add a field to User, Omit<User, 'password'> automatically includes it, while Pick<User, 'id' | 'name'> would not.