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.
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).
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:
MergeAll recursively processes the tuple by extracting the first element and merging it into an accumulator using the Merge helper typeMerge helper combines two objects by iterating over the union of all keys from both A and BA[K] | B[K]), which naturally collapses when one type is a subtype of the other (e.g., 1 | number simplifies to number){} as the accumulator and processes each element in the tuple left to right, building up the merged result incrementallyThis 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.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount