#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).

Loading...

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

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount