merge() function
Recursively merges source into target and returns a new object. Neither input is modified.
- Plain objects are merged recursively;
sourceproperties win. - Arrays are merged index by index ([1, 2, 3]merged with[9]is[9, 2, 3]). -undefinedinsourcedoes not overwrite an existingtargetvalue. - Any other value (Date, Map, Set, class instances, ...) replaces thetargetvalue as-is, and when the two sides are different kinds of containers,sourcereplacestarget. -__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 }