Was updating a bit of code today that returns optional props to a React component. I discovered that even though the function sometimes returns null
, it wouldn't error when the return value was immediately unpacked.
Pedantic summary of the code:
const returnPropsOrDont = (condition) => {
if (condition) return null;
return { optionalProp: 'foo' };
}
...
render() {
const { condition } = props;
return <SomeComponent
staticProp="staticProp"
{...returnPropsOrDont(condition)}
/>
}
Upon realizing this was cool, I ran to the console and tried it out on Objects and Arrays. Alas -
> {...null} // {}
> {...undefined} // {}, which is interesting because null is an object but undefined is not
> [...null] // Uncaught TypeError: object null is not iterable
I did some light Googling and found one article which suggests that TypeScript considers it a feature to make sure optionally defined values don't haunt an unsuspecting developer. Fine, but a) I'm not using TypeScript, and b) I have no idea why JS wouldn't guard Arrays in the same way.
Since this does seem like a guard against optionally defined values, why is {...null}
fine and [...null]
not?