typescript 47 lines · 7 steps

Type-safe deep merge in TypeScript

A recursive DeepPartial type and a matching merge function let you override any nested config field while keeping full type safety.

Explained by highlit
1type DeepPartial<T> = T extends object
2 ? { [K in keyof T]?: DeepPartial<T[K]> }
3 : T;
4 
5interface RequestConfig {
6 timeout: number;
7 retries: { count: number; backoff: number };
8 headers: Record<string, string>;
9 cache: { enabled: boolean; ttl: number };
10}
11 
12const defaultConfig: RequestConfig = {
13 timeout: 5000,
14 retries: { count: 3, backoff: 250 },
15 headers: { "Content-Type": "application/json" },
16 cache: { enabled: true, ttl: 60_000 },
17};
18 
19function isPlainObject(value: unknown): value is Record<string, unknown> {
20 return (
21 typeof value === "object" &&
22 value !== null &&
23 !Array.isArray(value)
24 );
25}
26 
27function mergeConfig<T>(base: T, overrides: DeepPartial<T>): T {
28 const result = { ...base } as T;
29 
30 for (const key of Object.keys(overrides) as (keyof T)[]) {
31 const override = overrides[key];
32 if (override === undefined) continue;
33 
34 const current = base[key];
35 if (isPlainObject(current) && isPlainObject(override)) {
36 result[key] = mergeConfig(current, override as DeepPartial<T[keyof T]>);
37 } else {
38 result[key] = override as T[keyof T];
39 }
40 }
41 
42 return result;
43}
44 
45export function resolveConfig(overrides: DeepPartial<RequestConfig> = {}): RequestConfig {
46 return mergeConfig(defaultConfig, overrides);
47}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Conditional plus mapped types can recurse through a whole object shape to make every nested field optional.
  2. 2A type guard like isPlainObject narrows unknown values so the compiler trusts your recursive merge.
  3. 3Pairing a recursive type with a recursive function keeps runtime behavior and static types in lockstep.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Type-safe deep merge in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code