#27932Medium

MergeAll

Merge variadic number of types into a new type. If the keys overlap, its values should be merged into an union. Learn union type manipulation, array type operations in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement MergeAll<XS>, a type that takes a tuple of object types and merges them into a single object, combining overlapping keys into union types.

Challenge Instructions: MergeAll

Medium

Merge variadic number of types into a new type. If the keys overlap, its values should be merged into an union.

For example:

type Foo = { a: 1; b: 2 }
type Bar = { a: 2 }
type Baz = { c: 3 }
 
type Result = MergeAll<[Foo, Bar, Baz]> // expected to be { a: 1 | 2; b: 2; c: 3 }

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
type cases = [
  Expect<Equal<MergeAll<[]>, {}>>,
  Expect<Equal<MergeAll<[{ a: 1 }]>, { a: 1 }>>,
  Expect<Equal<MergeAll<[{ a: string }, { a: string }]>, { a: string }>>,
  Expect<Equal<MergeAll<[{}, { a: string }]>, { a: string }>>,
  Expect<Equal<MergeAll<[{ a: 1 }, { c: 2 }]>, { a: 1; c: 2 }>>,
  Expect<
    Equal<
      MergeAll<[{ a: 1; b: 2 }, { a: 2 }, { c: 3 }]>,
      { a: 1 | 2; b: 2; c: 3 }
    >
  >,
  Expect<Equal<MergeAll<[{ a: 1 }, { a: number }]>, { a: number }>>,
  Expect<Equal<MergeAll<[{ a: number }, { a: 1 }]>, { a: number }>>,
  Expect<Equal<MergeAll<[{ a: 1 | 2 }, { a: 

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

type MergeAll<XS, Acc = {}> =
  XS extends [infer First, ...infer Rest]
    ? MergeAll<Rest, Merge<Acc, First>>
    : Acc;
 
type Merge<A, B> = {
  [K in keyof A | keyof B]:
    K extends keyof A
      ? K extends keyof B
        ? A[K] | B[K]
        : A[K]
      : K extends keyof B
        ? B[K]
        : never;
};

How it works:

This challenge helps you understand recursive tuple processing and object type merging with union values, and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge

Learn the Concepts