未知长度数组中所有对象的交集的打字稿类型 [英] Typescript type of intersection of all objects in array of unknown length
本文介绍了未知长度数组中所有对象的交集的打字稿类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Typescript 中有一个对象数组类型.让我们说:
I have a type of an array of object in Typescript. Let's say:
type Arr = [{ toto: string}, {titi: number}];
我事先不知道长度.我想要数组中所有对象的合并类型,即交集
I don't know the length in advance. I would like to have the type of the merge of all objects in the array, ie the intersection
{
toto: string,
titi: number
}
谢谢!
推荐答案
如您所见,您可以使用 Arr[number]
来获取数组中所有类型的联合.然后,您可以使用 UnionToIntersection
描述的此处进行转换它到一个路口:
As you discovered, you can use Arr[number]
to get a union of all types in the array. You can then use UnionToIntersection
described here to convert it to a intersection :
type Arr = [{ toto: string}, {titi: number}];
type UnionToIntersection<U> =
(U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never
type All = UnionToIntersection<Arr[number]>
这篇关于未知长度数组中所有对象的交集的打字稿类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文