0

I (only) use arguments to throw an error when an invalid number of arguments are passed to a function.

const myFunction = (foo) => {
  if (arguments.length !== 1) {
     throw new Error('myFunction expects 1 argument');
  }
}

Unfortunately in TypeScript I get the error The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression. when referenced in arrow function.

How can I (always) validate the number of arguments in TypeScript?

doberkofler
  • 9,511
  • 18
  • 74
  • 126
  • Possible duplicate of [Official information on \`arguments\` in ES6 Arrow functions?](https://stackoverflow.com/questions/30935336/official-information-on-arguments-in-es6-arrow-functions) – pushkin Jan 09 '19 at 21:01

2 Answers2

2

The code snippet that you posted doesn't seem to have the same error for me. I do see that error if I change it to be an arrow function:

const myFunction = (foo) => {
    if (arguments.length !== 1) {
        throw new Error('myFunction expects 1 argument');
    }
}

You can try doing something like:

const myFunction = (...foo) => {
    if (foo.length !== 1) {
        throw new Error('myFunction expects 1 argument');
    }
}

To work around the issue.

Matt H
  • 1,795
  • 1
  • 7
  • 8
2

You can also enforce the arity of your function in compile-time:

const myFunction = (...args: [any]) => {
  /* ... */
}
myFunction(1);    // OK
myFunction(1, 2); // Compile-time error
Karol Majewski
  • 23,596
  • 8
  • 44
  • 53