Partial, Pick, and Omit
`Pick<T, Keys>` creates a new type by selecting only certain properties from an existing type, while `Omit<T, Keys>` does the opposite, creating a new type with certain properties removed.
These utility types are extremely useful when you need a smaller or trimmed version of a larger type, such as showing only a subset of a User's fields in a public profile view.
type PublicUser = Omit<User, "password">;
type NameOnly = Pick<User, "name">;Pick
`Pick<User, "name">` produces a type containing only the name property from User, discarding all others.
Omit
`Omit<User, "password">` produces a type with every property of User except password, which is handy for hiding sensitive fields.
interface User {
name: string;
age: number;
password: string;
}
type NameOnly = Pick<User, "name">;
const n: NameOnly = { name: "Eve" };
console.log(n);{ name: 'Eve' }Pick keeps only the specified 'name' property from the User interface.
interface User {
name: string;
age: number;
password: string;
}
type PublicUser = Omit<User, "password">;
const pub: PublicUser = { name: "Eve", age: 29 };
console.log(pub);{ name: 'Eve', age: 29 }Omit removes the password property, leaving all other properties intact.
Key points
- Pick<T, Keys> selects only the listed properties from T.
- Omit<T, Keys> removes the listed properties from T.
- Both are useful for creating smaller, purpose-specific versions of a type.
- Keys are given as string literals or a union of string literals.
