Created
April 7, 2024 12:00
-
-
Save mimshins/a8a2f706a1eba26e8bfa6f527b4bf6ea to your computer and use it in GitHub Desktop.
Type-safe shallow merge of 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
type AnyObject = Record<keyof any, any>; | |
const isPlainObject = (x: unknown): x is AnyObject => { | |
return (x && typeof x === "object" && x.constructor === Object) as boolean; | |
}; | |
type Merged<T, S> = { [K in keyof S]: S[K] } & { | |
[K in keyof T]: K extends keyof S ? S[K] : T[K]; | |
}; | |
const shallowMerge = <T extends AnyObject, S extends AnyObject>( | |
target: T, | |
source: S, | |
): Merged<T, S> => { | |
if (!isPlainObject(target) || !isPlainObject(source)) { | |
throw new Error("Invalid inputs. Provide plain objects as inputs."); | |
} | |
return { ...target, ...source }; | |
}; | |
export default shallowMerge; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment