Check out this TypeScript function I wrote, it's designed to apply a patch to an object where the patch is a partial object of the same type:
function applyUpdate<T extends object>(obj: T, update: Readonly<Partial<T>>): T {
const updatedObj = { ...obj, ...update };
console.log(`obj: ${JSON.stringify(obj)}`);
console.log(`update: ${JSON.stringify(update)}`);
console.log(`updatedObj: ${JSON.stringify(updatedObj)}`);
return updatedObj;
}
This function seemed to work fine until I encountered a strange issue while testing it in the typescript playground.
It works for most cases, but not when the patch object is empty like this:{}
.
No matter what I try, I can't figure out why the output looks like this:
obj: {"id":"test","data":"testdata"}
patch: {}
patched: {"id":"test"}
How did the data
property just disappear in this scenario?
I was definitely expecting the data
property to remain intact after running this code.