Guillaume Wuip
Guillaume Wuip

Reputation: 363

Typescript type of intersection of all objects in array of unknown length

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

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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

Related Questions