Skip to content

merge() function

source 递归合并到 target 中并返回一个新对象。两个输入都不会被修改。

  • 纯对象(plain object)会被递归合并,source 的属性优先。
  • 数组按索引合并([1, 2, 3][9] 合并得到 [9, 2, 3])。
  • source 中的 undefined 不会覆盖 target 中已有的值。
  • 其他值(Date、Map、Set、类实例等)会原样替换 target 的值;当两侧容器类型不同时,source 替换 target
  • __proto__ 键会被跳过,因此合并不可信输入不会污染原型链。
  • 不支持循环结构。

Signature:

typescript
function merge<T extends object, S extends object>(target: T, source: S): T & S;
function merge<T extends object>(
  target: T,
): <S extends object>(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 }

// 与 pipe 一起使用 - 管道传入的对象优先于给定的默认值
pipe({ port: 3000 }, merge({ host: "localhost", port: 80 })); // { host: "localhost", port: 3000 }

Open Source Code

Released under the Apache-2.0 License.