diff --git a/src/object/merge.spec.ts b/src/object/merge.spec.ts index a9ab14aa0..1aa45b459 100644 --- a/src/object/merge.spec.ts +++ b/src/object/merge.spec.ts @@ -118,4 +118,12 @@ describe('merge', () => { expect(result).toEqual({ a: 2 }); expect(result.__proto__).toBe(Object.prototype); }); + + it('should handle top-level type mismatch consistently with nested behavior', () => { + const topLevelResult = merge(['1'] as any, { a: 2 }); + const nestedResult = merge({ x: ['1'] }, { x: { a: 2 } } as any); + + expect(topLevelResult).toEqual({ a: 2 }); + expect(nestedResult.x).toEqual({ a: 2 }); + }); }); diff --git a/src/object/merge.ts b/src/object/merge.ts index df7446917..102c99781 100644 --- a/src/object/merge.ts +++ b/src/object/merge.ts @@ -45,6 +45,16 @@ export function merge, S extends Record; for (let i = 0; i < sourceKeys.length; i++) { diff --git a/src/object/mergeWith.spec.ts b/src/object/mergeWith.spec.ts index c2b0be3d1..aad524367 100644 --- a/src/object/mergeWith.spec.ts +++ b/src/object/mergeWith.spec.ts @@ -125,4 +125,12 @@ describe('mergeWith', () => { expect(result).toEqual({ a: { b: { x: 1 }, c: { y: 2 }, d: { z: 3 } } }); }); + + it('should handle top-level type mismatch consistently with nested behavior', () => { + const topLevelResult = mergeWith(['1'] as any, { a: 2 }, () => undefined); + const nestedResult = mergeWith({ x: ['1'] }, { x: { a: 2 } } as any, () => undefined); + + expect(topLevelResult).toEqual({ a: 2 }); + expect(nestedResult.x).toEqual({ a: 2 }); + }); }); diff --git a/src/object/mergeWith.ts b/src/object/mergeWith.ts index ebec941ed..3e306bedb 100644 --- a/src/object/mergeWith.ts +++ b/src/object/mergeWith.ts @@ -54,6 +54,16 @@ export function mergeWith, S extends Record

any ): T & S { + if (Array.isArray(source)) { + if (!Array.isArray(target)) { + return mergeWith([] as unknown as T, source, merge); + } + } else if (isPlainObject(source)) { + if (!isPlainObject(target)) { + return mergeWith({} as unknown as T, source, merge); + } + } + const sourceKeys = Object.keys(source) as Array; for (let i = 0; i < sourceKeys.length; i++) {