英文:
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<X, {b: 2}>; // {a: 1, b: 2} | {a: 3, b: 2}
type b4 = Discriminator<X, {b: 4}>; // {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<T[number], U>` gets only the members of that union that match `U`
[See playground](https://www.typescriptlang.org/play?#code/MYewdgzgLgBAGjAvDA2gKBgbwIYC4YCMANDAEb4BMAvkRjvgMwnkzW1Z4wCsz+ALFTQBdGNggxQkKGjRQAngAcApjAAiASwjAATuoC26sNightAHgAqMJQA8oSsABNx2pdkfgANnJgBXMADWYCAA7mAoQiQAqgB8SDAAonba2MBQlihgvnqkStqRMLEy8spkFPEaWroGRibmJUogAGbwJJgs1DEA3DAA9L0c+MRklFQwAD6DMEwjrIL9MIsAegD8QA)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论