【问题标题】:pick properties with values of given type选择具有给定类型值的属性
【发布时间】:2018-12-18 22:40:50
【问题描述】:

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

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

所以不知何故我需要选择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}

【问题讨论】:

  • 你想让PickOfValue&lt;{a: unknown, b: string | number, c: string, d: number, e: "", f: 0}, string | number&gt;返回什么?
  • {a: string | number, b: string, c: number, d: "", e: 0} 因为所有值都匹配
  • 对不起,我编辑了它...再检查一下?
  • b: string | number, c: string, d: number, e: "", f: 0},因为unknown extends string | number 是假的,但它匹配anynever 类型
  • 刚刚检查,谢谢!

标签: typescript


【解决方案1】:

我可能会这样实现它:

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>>

KeysOfValue 类型函数使用mappedconditional 类型来拉出相关键。

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

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

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

【讨论】:

  • 哇,我太累了,我自己永远也想不通,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-02
  • 2012-11-30
  • 1970-01-01
  • 2014-12-08
  • 2021-03-29
  • 2013-07-20
相关资源
最近更新 更多