DS
Back to TypeScript

deep-merge.ts

typescript/utils/deep-merge.ts
TypeScript

Recursive deep merge of two objects with proper TypeScript generics.

deep-merge.ts
/**
 * @description Recursive deep merge of two objects with proper TypeScript generics.
 * @tags utility, objects, merge, recursive
 */
export function deepMerge<T extends Record<string, unknown>>(
  target: T,
  source: Partial<T>
): T {
  const result = { ...target };

  for (const key in source) {
    const sourceVal = source[key];
    const targetVal = result[key];

    if (
      sourceVal !== null &&
      typeof sourceVal === "object" &&
      !Array.isArray(sourceVal) &&
      targetVal !== null &&
      typeof targetVal === "object" &&
      !Array.isArray(targetVal)
    ) {
      result[key] = deepMerge(
        targetVal as Record<string, unknown>,
        sourceVal as Record<string, unknown>
      ) as T[typeof key];
    } else if (sourceVal !== undefined) {
      result[key] = sourceVal as T[typeof key];
    }
  }

  return result;
}