javascriptoptional-chainingnullish-coalescing

Destructuring an optionally chained object, to get the ...rest?


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?


Solution

  • 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:

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