← All Exercises

Generic Deep Merge for Config Objects

advancedtypescript~15min

Background

Layered configuration merges defaults, environment files, and runtime overrides. A shallow spread loses nested settings, while a naive recursive merge may mutate inputs or concatenate arrays unexpectedly.

Problem

Implement deepMerge<T>(base, patch) that recursively merges plain objects, replaces arrays instead of concatenating them, ignores undefined patch values, and never mutates base. Type the patch as DeepPartial<T> so nested optional fields are accepted while unrelated keys are rejected.

Input

A JSON object with base and patch, both JSON objects that may share nested keys.

Output

A JSON object representing the merged configuration, with base key order preserved and new keys appended.

Sample tests

Sample 1

Input: {"base":{"user":{"name":"Ada","tags":["a"]},"active":true},"patch":{"user":{"tags":["b","c"],"age":36},"active":false,"extra":null}}
Expected: {"user":{"name":"Ada","tags":["b","c"],"age":36},"active":false,"extra":null}

Sample 2

Input: {"base":{"user":{"name":"Ada","tags":["a"]},"active":true},"patch":{"user":{"tags":[]}}}
Expected: {"user":{"name":"Ada","tags":[]},"active":true}

Your solution

Learning objective

Practice mapped types, recursive generics, and immutable object updates for layered configuration.