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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.