选择具有给定类型值的属性

Roo*_*omy 3 typescript

我想要一个类型,它允许我只从对象中选择那些值扩展给定类型的属性,例如:

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

所以不知何故,我需要选择T其值是一种类型的键(属性) V(条件T[P] extends Vtrue),我找不到任何方法来解决这个问题,所以在这里询问是我最后的帮助手段。

结果示例:

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}
Run Code Online (Sandbox Code Playgroud)

jca*_*alz 5

我可能会像这样实现它:

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>>
Run Code Online (Sandbox Code Playgroud)

typeKeysOfValue函数使用映射的条件类型来提取相关键。

这会为您的示例产生以下结果:

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

假设这就是您想要看到的,那么它就有效。希望有帮助;祝你好运!