This page looks best with JavaScript enabled

Allow more or less no. of arguments in Typescript functions

 ·   ·  ☕ 2 min read

Allow additional arguments or optional arguments for function calls in Typescript.

Consider the below example of a function that adds two numbers.

1
2
3
4
5
6
function getSum(i: number, j: number): number {
  return i + j;
}

console.log(getSum(1, 2));
// 3

This works fine and as expected, but what happens when there is a discrepancy in number of arguments.

1
2
3
4
5
6
7
function getSum(i: number, j: number): number {
  return i + j;
}

console.log(getSum(1));
// error TS2554: Expected 2 arguments, but got 1.
// An argument for 'j' was not provided.

The above error is perfect.

Except for the fact that Javascript does not behave this way. So, we can mess up functions, modules and classes when incrementally migrating them to Typescript.

Optional arguments

Fortunately, Typescript has a work-around. You can make the last variable as optional.

1
2
3
4
5
6
function getSum(i: number, j?: number) {
  return i + j;
}

console.log(getSum(1));
// NaN

We did not get compilation errors, but runtime errors continue to happen.

And, you guessed it - there is a work-around for that too. We just revert to the our old friend - argument defaults.

1
2
3
4
5
6
function getSum(i: number, j: number = 0) {
  return i + j;
}

console.log(getSum(1));
// 1

Additional arguments

Additional arguments supplied to the function throws error similar to the previous cases but with a complaint and loud houl about providing more than necessary.

1
2
3
4
5
6
function getSum(i: number, j: number) {
  return i + j;
}

console.log(getSum(1, 2, 3));
// error TS2554: Expected 2 arguments, but got 3

We work-around the problem of additional parameters by taking some help from another old friend of the good guys - rest operator.

1
2
3
4
5
6
function getSum(i: number, j: number, ...k: number[]) {
  return i + j;
}

console.log(getSum(1, 2, 3));
// 3
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things