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 Tstores all possible keys ofTinP- The
asusesPto accessT[P]and get its value - We then go into the conditional where it checks if
T[P]matchesValue | undefined(undefinedto allow for optional properties). - If the value of
T[P]matchesValue | undefined, we then setPas property of the type and its corresponding value ofT[P] - Type properties set to
neverdon’t end up in the resulting type, explicitly removing any properties that don’t match the type you want to pick.