Skip to content

函数: deepMerge()

ts
function deepMerge<T>(...sources): UnionToIntersection<Exclude<T[number], null | undefined>>;

定义于: object.ts:111

深合并多个对象,返回全新对象(不改动任何入参),与 deepClone / deepEqual 同族。

类型参数

类型参数
T extends (Record<string, any> | null | undefined)[]

参数

参数类型描述
...sourcesT任意个待合并对象,靠后的覆盖靠前的;null / undefined 会被跳过

返回值

UnionToIntersection<Exclude<T[number], null | undefined>>

合并后的新对象

备注

  • 只深合并普通对象(字面量对象);数组、Date、class 实例等按整体覆盖(后者替换前者,按引用取用,不逐项合并);
  • 不改动入参(普通对象会被递归克隆进结果),但被覆盖的数组/实例是引用,如需完全隔离请先 deepClone

示例

ts
deepMerge({ a: 1, b: { c: 1 } }, { b: { d: 2 }, e: 3 }) // => { a: 1, b: { c: 1, d: 2 }, e: 3 }
deepMerge({ a: 1 }, { a: 2 })                            // => { a: 2 }(标量覆盖)
deepMerge({ list: [1, 2] }, { list: [3] })              // => { list: [3] }(数组整体覆盖)
deepMerge({ a: 1 }, null, { b: 2 })                     // => { a: 1, b: 2 }(跳过 null)