Reputation: 363
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
}
Thanks!
Upvotes: 0
Views: 1210
Reputation: 249886
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]>
Upvotes: 3