When using spread operator , prevent overwriting keys with new value undefined
Consider an object bleh1
and bleh2
const bleh1 = {
name: "ajnskdas",
foo: "oof",
bar: "something"
}
const bleh2 = {
foo: "oofElse",
bar: undefined,
booz: "chilled"
}
bleh2.bar
should overwrite key bar
only if value is not undefined
const bleh3 = {...bleh1, ...bleh2}
// Actual
// {
// "name": "ajnskdas",
// "foo": "oofElse",
// "bar": undefined,
// "booz": "chilled"
// }
// Desired
// {
// "name": "ajnskdas",
// "foo": "oofElse",
// "bar": "something",
// "booz": "chilled"
// }
I can do it during runtime with function removeEmpty
but type/interface of bleh4
wont have new keys of bleh2
ie bleh4.booz
is not inferred by typescript
function removeEmpty(obj: any) {
return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
}
const bleh4 = { ...bleh1, ...removeEmpty(bleh2) }