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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Conditional plus mapped types can recurse through a whole object shape to make every nested field optional.
- 2A type guard like isPlainObject narrows unknown values so the compiler trusts your recursive merge.
- 3Pairing a recursive type with a recursive function keeps runtime behavior and static types in lockstep.
Related explainers
typescript
import { Controller } from '@nestjs/common'; import { MessagePattern, Payload,
Manual RabbitMQ acks in a NestJS controller
microservices
message-queue
acknowledgement
Intermediate
8 steps
typescript
type LazyImageOptions = { rootMargin?: string; loadedClass?: string; };
Lazy-loading images with IntersectionObserver
intersectionobserver
lazy-loading
performance
Intermediate
7 steps
typescript
type CurrencyFormatOptions = { locale?: string; currency: string; showDecimals?: boolean;
Caching Intl.NumberFormat for currency
memoization
internationalization
caching
Intermediate
9 steps
typescript
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-card',
Multi-slot content projection in Angular
content-projection
components
templates
Intermediate
7 steps
typescript
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository, DeepPartial } from 'typeorm'; import { User } from './entities/user.entity';
Building a CRUD service in NestJS
crud
dependency-injection
repository-pattern
Intermediate
7 steps
python
from copy import deepcopy from typing import Any, Mapping
How a recursive deep merge works in Python
recursion
immutability
dictionaries
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/type-safe-deep-merge-in-typescript-explained-typescript-469b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.