deepMerge.ts
type DeepPartial<T> = {
[P in keyof T]?: DeepPartial<T[P]>
}
function deepMerge<T extends { [key: string]: any }>(
target: T,
source: DeepPartial<T>,
): T {
if (Array.isArray(target)) {
return target.concat(source) as unknown as T
}
if (
target &&
source &&
typeof target === 'object' &&
typeof source === 'object'
) {
return Object.assign(
target,
...Object.keys(source).map((key) => ({
[key]: deepMerge(
target[key as keyof T],
source[key as keyof T] as DeepPartial<T[keyof T]>,
),
})),
)
}
return source as T
}
Пример
deepMerge({ a: 'a', b: 'b' }, { a: 'a', c: 'c' }) // => {a: "a", b: "b", c: "c"}