Allow more or less no. of arguments in Typescript functions

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

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

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.

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.

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.

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.

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.

function getSum(i: number, j: number, ...k: number[]) {
  return i + j;
}

console.log(getSum(1, 2, 3));
// 3
comments powered by Disqus