1

Would it by possible, in TypeScript, to create a function which will be used like this:

foo(
  { key1: 'hello' },
  { key2: 5 },
  { key3: true },
)

and it would return a type like below?

{
  key1: string,
  key2: number,
  key3: boolean,
}

The function would ideally allow arbitrary number of arguments. This is something like an intersection of arbitrary number of types.

There is this question which asks for something similar, but they have the array of types declared as const in a variable.

I suspect that what I suggest is not possible but looking forward to be surprised.

lishaak
  • 416
  • 2
  • 11

1 Answers1

1

Here's an approach that uses a recursive type to dynamically compute an intersection type that represents the merged result object:

type Merge<T extends unknown[]> = T extends [infer U, ...infer V]
  ? { [K in keyof U]: U[K] } & Merge<V>
  : {};

function foo<T extends object[]>(...args: T): Merge<T>  {
  return Object.assign({}, ...args);
}

Playground link with examples

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156