Skip to content

Instantly share code, notes, and snippets.

@krzysztofMlczk
Created June 23, 2023 10:21
Show Gist options
  • Save krzysztofMlczk/fd55be58c55f68de722fc14d1f3e7165 to your computer and use it in GitHub Desktop.
Save krzysztofMlczk/fd55be58c55f68de722fc14d1f3e7165 to your computer and use it in GitHub Desktop.
Deep merge two objects
export type DeepPartial<T> = {
[P in keyof T]?: DeepPartial<T[P]>;
};
function isObject(item: any): boolean {
return item && typeof item === 'object' && !Array.isArray(item);
}
export function merge<T>(target: T, source: DeepPartial<T>): T {
for (const key in source) {
const targetValue = target[key];
const sourceValue = source[key];
if (sourceValue === undefined) {
continue;
}
if (isObject(targetValue) && isObject(sourceValue)) {
target[key] = merge(targetValue, sourceValue);
} else {
target[key] = sourceValue as T[typeof key];
}
}
return target;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment