TypeScriptUtility types

Pick<Type, Keys>

Creates a type containing only selected properties of another type.

On this page

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 Pick update themselves automatically when the source type changes.

Related entries

#

Spotted a mistake or missing an example? Write to us.