Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pick properties with values of given type

Tags:

typescript

I want to have a type which would allow me to pick only those properties from object which value extends given type, as in example:

type PickOfValue<T, V extends T[keyof T]> = {
    [P in keyof (key-picking magic?)]: T[P];
};

so somehow I need to pick keys (properties) of T which values are a type of V (condition T[P] extends V is true), I couldn't find any way to approach that so asking here is my last resort of help.

example result:

PickOfValue<Response, () => Promise<any>>; // {json: () => Promise<any>, formData: () => Promise<FormData>, ...}
PickOfValue<{a: string | number, b: string, c: number, d: "", e: 0}, string | number>; // {a: string | number, b: string, c: number, d: "", e: 0}
like image 836
Roomy Avatar asked Oct 21 '25 10:10

Roomy


1 Answers

I would probably implement it like so:

type KeysOfValue<T, V extends T[keyof T]> = 
  { [K in keyof T]-?: T[K] extends V ? K : never }[keyof T];

type PickOfValue<T, V extends T[keyof T]> = Pick<T, KeysOfValue<T, V>>

The KeysOfValue type function uses a mapped, conditional type to pull out the relevant keys.

This yields the following result for your example:

type Example = PickOfValue<Response, () => Promise<any>>; 
// type Example = {
//  arrayBuffer: () => Promise<ArrayBuffer>;
//  blob: () => Promise<Blob>;
//  formData: () => Promise<FormData>;
//  json: () => Promise<any>;
//  text: () => Promise<string>;
// }

Assuming that's what you want to see, then it works. Hope that helps; good luck!

like image 130
jcalz Avatar answered Oct 23 '25 00:10

jcalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!