0

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!

Guillaume Wuip
  • 343
  • 5
  • 13

1 Answers1

3

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]>
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357