Skip to content

Instantly share code, notes, and snippets.

@mimshins
Created April 7, 2024 12:00
Show Gist options
  • Save mimshins/a8a2f706a1eba26e8bfa6f527b4bf6ea to your computer and use it in GitHub Desktop.
Save mimshins/a8a2f706a1eba26e8bfa6f527b4bf6ea to your computer and use it in GitHub Desktop.
Type-safe shallow merge of two objects
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