如何提取所有在常量数组中扩展查询类型的对象的联合类型?

huangapple go评论60阅读模式
英文:

How to extract the union type of all objects in a constant array that extend a query type?

问题

const X = [
 {a: 1, b: 2},
 {a: 3, b: 2},
 {a: 5, b: 4}
] as const satisfies {a: any};

type b2 = Discriminator<X, {b: 2}>; // {a: 1, b: 2} | {a: 3, b: 2}
type b4 = Discriminator<X, {b: 4}>; // {a: 5, b: 4}
英文:

I have a constant array with objects that satisfy a type:

const X = [
 {a: 1, b: 2},
 {a: 3, b: 2},
 {a: 5, b: 4}
] as const satisfies {a: any};

Is there a way to get the union type of all the elements that extend a generic type that I pass. For example:

type b2 = Discriminator&lt;X, {b: 2}&gt;; // {a: 1, b: 2} | {a: 3, b: 2}
type b4 = Discriminator&lt;X, {b: 4}&gt;; // {a: 5, b: 4}

答案1

得分: 1

type Discriminator<T extends readonly unknown[], U> = Extract<T[number], U>

这里的 Discriminator 是一个类型,接受对象数组作为 T,以及要匹配的内容作为 U

T[number] 以联合类型的形式获取数组的所有可能成员类型,然后 Extract<T[number], U> 仅获取与 U 匹配的成员。


<details>
<summary>英文:</summary>

type Discriminator<T extends readonly unknown[], U> = Extract<T[number], U>


Here `Discriminator` is a type that accepts the array of objects as `T` and something to match against as `U`.

`T[number]` gets all possible array member types as a union, and then `Extract&lt;T[number], U&gt;` gets only the members of that union that match `U`

[See playground](https://www.typescriptlang.org/play?#code/MYewdgzgLgBAGjAvDA2gKBgbwIYC4YCMANDAEb4BMAvkRjvgMwnkzW1Z4wCsz+ALFTQBdGNggxQkKGjRQAngAcApjAAiASwjAATuoC26sNightAHgAqMJQA8oSsABNx2pdkfgANnJgBXMADWYCAA7mAoQiQAqgB8SDAAonba2MBQlihgvnqkStqRMLEy8spkFPEaWroGRibmJUogAGbwJJgs1DEA3DAA9L0c+MRklFQwAD6DMEwjrIL9MIsAegD8QA)

</details>



huangapple
  • 本文由 发表于 2023年6月22日 01:43:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525904.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定