Deviopath › TypeScript

Deep Merge

Medium · Generics

Write deepMerge<T, U>(target: T, source: U): T & U that returns a NEW object (do not modify the inputs). Start from a copy of target, then for every key of source:

- If the source value is undefined, skip the key.

- If both values are plain objects (not null, not arrays), merge them recursively.

- If both values are arrays, the result is the target items followed by the source items.

- Otherwise the source value wins (this includes null).

Next: Friend Groups with Union-Find