TypeScriptUtility types
Pick<Type, Keys>
Creates a type containing only selected properties of another type.
Example
#TypeScript
interface User {
id: number
name: string
email: string
passwordHash: string
}
type PublicUser = Pick<User, 'id' | 'name'>
function toPublic(user: User): PublicUser {
return { id: user.id, name: user.name }
}
console.log(toPublic({ id: 7, name: 'Emma', email: 'e@x.com', passwordHash: '…' }))Result
{ id: 7, name: 'Emma' }Definition and usage
#Pick<Type, Keys> selects only the given fields from a type. Pick<User, "id" | "name"> is an object with just the id and name fields, with exactly the same types as in User.
It’s useful when a component or function needs only a fragment of a larger object. That way you don’t have to pass or create the full object, and the type stays linked to its source.
The keys must exist on the source type. A typo in a field name gets reported by the compiler.
Syntax
#Syntax
type New = Pick<Type, "field1" | "field2">Type parameters
#Type
object type
The source type.Keys
union of Type’s keys
The fields that should remain in the new type.
Good practices
#- When it’s easier to list the fields to remove than the ones to keep, use
Omit. - Types derived through
Pickupdate themselves automatically when the source type changes.
Related entries
#- Pick vs OmitPick<Type, Keys> selects only the given fields from a type, while Omit<Type, Keys> copies every field except the given ones.
- Omit<Type, Keys>Creates a type without selected properties of another type.
- Partial<Type>Creates a type where every property is optional.
- keyofCreates a union of the key names of a given object type.
- Record<Keys, Type>Creates an object type with given keys, where every value has the same type.
Spotted a mistake or missing an example? Write to us.