1

Is it possible to take a tuple of different objects, and get a type of all of these objects combined? For example if i have a tuple like this:

const t = tuple({current: 1}, {old: 2}, {new: 3}); //this should be interpreted as [{current: number;}, {old: number;}, {new: number;}]

and then i combine those objects into a single one:

let newob = {};
for(let ob of t) {
  Object.assign(newob, ob);
}

can I somehow make typescript treat this new object as a

typeof t[0] & typeof t[1] & typeof t[2]

which in this case would be

{current: number; old: number; new: number;}

without manually typing that all?

I'd like it to work with any tuple and any objects inside tuple

ncpa0cpl
  • 192
  • 1
  • 13

1 Answers1

1

You can capture the parameters in a tuple type using a generic type parameter with a constraint of any[] for a rest parameter. You can the use UnionToIntersection described here to merge all tuple item types into a single intersection type

type UnionToIntersection<U> = 
  (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never
function tuple<T extends any[]>(...t: T) {
  let newob = {} as UnionToIntersection<T[number]>;
  for (let ob of t) {
    Object.assign(newob, ob);
  }
  return newob;
}

Playground Link

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • Thanks, this does work. However I noticed a strange behavior, it isn't really a big problem, but if you try to put into tuple two class instance objects, and both of them have a private method of the same name, the whole thing return type of 'never'. Doesn't happen if methods are public or protected. [Here's demo](https://stackblitz.com/edit/nh1q1d?file=index.ts) – ncpa0cpl Oct 29 '20 at 16:33