xxm-test-js
Version:
xxm-js通用js工具(utils)库
38 lines (37 loc) • 1.22 kB
TypeScript
/**
* 对象类型约束
*/
type PlainObject = Record<string, unknown>;
/**
* 深度合并类型推断
*/
type DeepMerge<T, U> = {
[K in keyof T | keyof U]: K extends keyof U ? K extends keyof T ? T[K] extends PlainObject ? U[K] extends PlainObject ? DeepMerge<T[K], U[K]> : U[K] : U[K] : U[K] : K extends keyof T ? T[K] : never;
};
/**
* 递归合并两个或多个对象
* Copyright (c) 2024 xxm
*
* @template T - 目标对象类型
* @template U - 源对象类型
* @param {T} target - 目标对象
* @param {U} source - 源对象
* @param {...PlainObject[]} sources - 更多源对象(可选)
* @returns {DeepMerge<T, U>} 返回合并后的新对象
* @example
*
* ```ts
* // 合并两个对象
* const obj1 = { a: 1, b: { c: 2 } };
* const obj2 = { b: { d: 3 }, e: 4 };
* const result = deepMerge(obj1, obj2);
* // 结果: { a: 1, b: { c: 2, d: 3 }, e: 4 }
*
* // 合并多个对象
* const obj3 = { f: 5 };
* const result2 = deepMerge(obj1, obj2, obj3);
* // 结果: { a: 1, b: { c: 2, d: 3 }, e: 4, f: 5 }
* ```
*/
export declare function deepMerge<T extends PlainObject, U extends PlainObject>(target: T, source: U, ...sources: PlainObject[]): DeepMerge<T, U>;
export {};