4 min read
•Question 14 of 48mediumWhat are Pick and Omit utility types?
Selecting or excluding properties.
What You'll Learn
- Pick<T, K> utility
- Omit<T, K> utility
- Use cases
Pick<T, K>
Creates a type with only the specified properties.
code.tsTypeScript
interface User {
id: string;
name: string;
email: string;
password: string;
createdAt: Date;
}
// Only pick specific properties
type UserPreview = Pick<User, "id" | "name">;
// { id: string; name: string; }
type LoginCredentials = Pick<User, "email" | "password">;
// { email: string; password: string; }Omit<T, K>
Creates a type excluding the specified properties.
code.tsTypeScript
// Exclude sensitive data
type PublicUser = Omit<User, "password">;
// { id: string; name: string; email: string; createdAt: Date; }
// Exclude multiple properties
type UserInput = Omit<User, "id" | "createdAt">;
// { name: string; email: string; password: string; }Common Patterns
code.tsTypeScript
// API response without internal fields
type ApiUser = Omit<User, "password" | "createdAt">;
// Form data type
type UserForm = Pick<User, "name" | "email" | "password">;
// Combine with Partial for updates
type UserUpdate = Partial<Pick<User, "name" | "email">>;