6

Suppose I have a function that takes a destructured object as a parameter in an arrow function:

const myFunc = ({a, b, c}) => {
};

Is there anyway or syntax that would allow me to get that whole object as a single value as well? Since the arrow function doesn't bind arguments, I can't use that.

Is it possible to name it, something along the lines of:

const myFunc = (allArgs: {a, b, c}) => {
    console.log(allArgs);
};
myFunc({a:1, b:2, c:3}); // Output: {a:0, b:1, c: 2}

Obviously, this isn't a deal breaker and there are plenty of workarounds (either don't use an arrow function, don't destructure, or recreate the object when I need it), but I'd like to know for convenience sake.

samanime
  • 25,408
  • 15
  • 90
  • 139

1 Answers1

11

You could destructure a single param quite easily. You lose the advantage of the terse destructuring syntax in the arguments, but it's easy and still clear:

const myFunc = (allArgs) => {
    const {a, b, c} = allArgs;
    console.log(allArgs);
};

Alternatively, consider whether you need an arrow function. If you don't need access to the lexical this perhaps a good old-fashioned function() {} will do the trick and give you access to arguments.

JVDL
  • 1,157
  • 9
  • 16
  • Thanks, those are both good possibilities. I'd definitely considering using a normal `function` syntax, but hadn't though of just destructing immediately in the method. That's a relatively clean approach. – samanime Nov 13 '16 at 02:50
  • Unfortunately this is no longer an expression, which means you typically also need an extra `return` at the end. – user239558 Mar 15 '19 at 11:14
  • It actually solves the question, why isn't it accepted? – vintprox Aug 30 '19 at 03:15