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

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
javascript
function evaluate(expression) {
  const tokens = tokenize(expression);
  let pos = 0;
 

Building a recursive descent calculator

parsing recursion operator-precedence
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
typescript
import { useEffect, useState } from "react";
 
interface Section {
  id: string;

Building a scroll-spy hook in React

custom-hooks intersectionobserver dom-observation
Intermediate 8 steps

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