TypeScript: pick properties with a defined type

Using Typescript 4.1, this can be made even shorter, while also allowing to pick optional properties, which the other answers don’t allow:

type PickByType<T, Value> = {
  [P in keyof T as T[P] extends Value | undefined ? P : never]: T[P]
}

As an explanation what happens here, because this might come across as black magic:

  1. P in keyof T stores all possible keys of T in P
  2. The as uses P to access T[P] and get its value
  3. We then go into the conditional where it checks if T[P] matches Value | undefined (undefined to allow for optional properties).
  4. If the value of T[P] matches Value | undefined, we then set P as property of the type and its corresponding value of T[P]
  5. Type properties set to never don’t end up in the resulting type, explicitly removing any properties that don’t match the type you want to pick.

Leave a Comment