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!

1
  • I've tried Arr[number] but this gave us the union {toto: string}|{toto:number} Commented Oct 9, 2019 at 18:56

1 Answer 1

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]>
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice :) I was trying to write something recursive. Thanks a lot !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.