TypeScript Deep Merge Utility

7.0.3 · active · verified Sun Apr 19

ts-deepmerge is a TypeScript utility library providing a robust deep merge function. It automatically infers the return type based on input objects without mutating the source objects, a key differentiator from many mutable merge utilities. Objects and arrays are merged recursively, while primitive values like numbers and strings are overwritten. Merging occurs in the order of arguments provided, giving precedence to later arguments. The current stable version is 7.0.3. As a utility library, its release cadence is driven by new features, bug fixes, or TypeScript version updates rather than a strict schedule. It differentiates itself by strong TypeScript type inference and non-mutation by default, supporting both ESM and CommonJS environments. It also offers an `options` mechanism to customize merge behavior, such as how arrays are handled.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic deep merging of multiple objects and using `merge.withOptions` to customize array merging behavior.

import { merge } from 'ts-deepmerge';

const obj1 = {
  a: {
    a: 1
  },
  array: [1, 2]
};

const obj2 = {
  b: {
    a: 2,
    b: 2
  },
  array: [3, 4]
};

const obj3 = {
  a: {
    b: 3
  },
  b: {
    b: 3,
    c: 3
  },
  c: 3,
  array: [5, 6]
};

// Basic deep merge
const resultBasic = merge(obj1, obj2, obj3);
console.log('Merged Result (default):', resultBasic);
/*
{ a: { a: 1, b: 3 }, b: { a: 2, b: 3, c: 3 }, array: [ 1, 2, 3, 4, 5, 6 ], c: 3 }
*/

// Merge with options, e.g., to overwrite arrays instead of merging them
const resultWithOptions = merge.withOptions(
  { mergeArrays: false },
  obj1, 
  obj2
);
console.log('Merged Result (mergeArrays: false):', resultWithOptions);
/*
{ a: { a: 1 }, array: [ 3, 4 ] }
*/

view raw JSON →