I have typical problem with javascript. Say, I have an input object, which, in some cases, could be enrich with additional keys. I have two options how to do that. First:
function enrich(input, optionalData) {
return {
...input,
additionalKey: optionalData
}
}
Now I could have an object with { additionalKey: undefined }, which could lead to bugs. For example, additionalKey will be lost after JSON.stringify/parse. Another bug: check key with operator in
('additionalKey' in obj), which gives true, but the value is actually undefined → we have to write additional code which checks the value also.
Another option here is
function enrich(input, optionalData) {
const output = { ...input }
if (typeof optionalData !== 'undefined') {
output.additionalKey = optionalData
}
return output
}
which gives us 3 more lines of code per key, and also cannot be properly typed with typescript.
What I propose:
function enrich(input, optionalData) {
return {
...input,
additionalKey?: optionalData
}
}
if optionalData is undefined, then additionalKey will not be added to the output object.