Variable Number of Arguments in TypeScript

February 16th 2018 TypeScript JavaScript

JavaScript has always supported functions with variable number of arguments, although the syntax required some getting used to. In TypeScript and ECMAScript 6 rest parameters and spread syntax provide a more convenient alternative that also works with arrow functions.

The JavaScript Way

There is an arguments object available in every JavaScript function as a local variable. It contains the array of arguments that where passed to the function:

function varArgs() {
  console.log(arguments.length);
}

To pass the array to another function accepting a variable number of arguments, the apply function can be used:

function varArgs() {
  console.log.apply(console, arguments);
}

If you try to use the arguments object inside an arrow function, it won't work:

The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression.

Instead of using a function and manually handling this value, you can now use rest parameters and spread syntax.

The TypeScript / ECMAScript 6 Way

Rest parameters can be used to capture variable number of arguments into an array in a way similar to other C-like languages:

function varArgs(...args: any[]) {
  console.log(args.length);
}

To pass the array to a function accepting a variable number of arguments, spread syntax can be used:

function varArgs(...args: any[]) {
  console.log(...args);
}

This approach works just as well with arrow functions:

let varArgs = (...args: any[]) => {
  console.log(...args);
}
Copyright
Creative Commons License