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:
P in keyof T
stores all possible keys ofT
inP
- The
as
usesP
to accessT[P]
and get its value - We then go into the conditional where it checks if
T[P]
matchesValue | undefined
(undefined
to allow for optional properties). - If the value of
T[P]
matchesValue | undefined
, we then setP
as property of the type and its corresponding value ofT[P]
- 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.