Created
June 23, 2023 10:21
-
-
Save krzysztofMlczk/fd55be58c55f68de722fc14d1f3e7165 to your computer and use it in GitHub Desktop.
Deep merge two objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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