0

I have this setup

const { discard_me, ...rest } = some?.optional?.chaining;

I end up with an error that discard_me doesn't exist, but that's expected if chaining is also non-existent. It seems like the optional chaining should cover the concerns of both the left and right hand side of the assignment.

Is there a way round this without nullish coalescing?

AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173
  • 5
    What's wrong with adding `|| {}` or `?? {}` – adiga Jul 06 '20 at 16:47
  • Because that should/could be handled by the optional chaining? – AncientSwordRage Jul 06 '20 at 16:51
  • 1
    It's not. These are two separate concerns; the RHS resolves to either `some.optional.chaining` or `undefined`, and the latter definitely can't be destructured (also the former *maybe* can't be). – jonrsharpe Jul 06 '20 at 16:52
  • That is what nullish coalescing is for. [MDN even has an example combining both](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining#Combining_with_the_nullish_coalescing_operator) – adiga Jul 06 '20 at 16:52
  • 1
    Does this answer your question? [destructuring falsey and null with default parameters](https://stackoverflow.com/questions/39522014/destructuring-falsey-and-null-with-default-parameters) – Mr. Polywhirl Jul 06 '20 at 16:53
  • @jonrsharpe that would be an excellent answer – AncientSwordRage Jul 06 '20 at 16:53
  • 1
    The answer is simply, `const { discard_me, ...rest } = some?.optional?.chaining || {}` as you cannot destructure `undefined`. This will not throw the error anymore. – Mr. Polywhirl Jul 06 '20 at 16:54
  • @jonrsharpe I got this question opened so you'd have an opportunity to answer it with your comment. I would really appreciate that. – AncientSwordRage Jul 07 '20 at 09:21

1 Answers1

1

It seems like the optional chaining should cover the concerns of both the left and right hand side of the assignment.

It doesn't, because some?.optional?.chaining is either going to resolve to:

  • some.optional.chaining (which may be undefined); or
  • undefined (which definitely is).

For the destructuring assignment, the right-hand side must be an object.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437