Skip to content

merge() function

Recursively merges source into target and returns a new object. Neither input is modified.

  • Plain objects are merged recursively; source properties win. - Arrays are merged index by index ([1, 2, 3] merged with [9] is [9, 2, 3]). - undefined in source does not overwrite an existing target value. - Any other value (Date, Map, Set, class instances, ...) replaces the target value as-is, and when the two sides are different kinds of containers, source replaces target. - __proto__ keys are skipped, so merging untrusted input cannot pollute the prototype chain. - Circular structures are not supported.

Signature:

typescript
declare function merge<T extends object, S extends object>(target: T, source: S): T & S;

Example

ts
merge({ a: 1, b: { c: 2 } }, { b: { d: 3 } }); // { a: 1, b: { c: 2, d: 3 } }
merge({ a: [1, 2, 3] }, { a: [9] }); // { a: [9, 2, 3] }
merge({ a: 1 }, { a: undefined }); // { a: 1 }

// with pipe - the piped object wins over the given defaults
pipe(
  { port: 3000 },
  merge({ host: "localhost", port: 80 }),
); // { host: "localhost", port: 3000 }

Open Source Code

Released under the Apache-2.0 License.