Typescript Rest and Spread Operator

Scenario

We wish to have a function where we can pass in any number of arguments and add them together. So for example:

sum(1,2)

or

sum(1,2,3)

Also we want another function where we can subtract the first argument from the sum of the rest. Like this:

addThenSubtract(1,2,3) // Result would be 4addThenSubtract(1,2,3,4) // Result would be 8

The SPREAD operator is also expressed as ... . We will see this used when we implement addThenSubtract .

Approach

Sum

We implement sum like this.

function sum(...arr: number[]): number {
let sum = 0;
arr.forEach((v) => {
sum += v;
});
return sum;
}

The REST operator collects all the arguments into an an array arr for us, and we then calculate the sum.

addThenSubtract

Here we can subtract the first argument from the sum of the rest.

/**
* @param subtract Subract this number from the numbers added
* @param add Add tese numbers together
*/
function addThenSubtract(subtract: number, ...add: number[]) {
console.log(`subtract ${subtract}`);
console.log(`add ${add}`);
const total = sum(...add);
return total - subtract;
}

Note that when we call add we use an operator that looks like the REST operator ... . In this context it’s a SPREAD operator. It takes the values in the array and spreads them out. So if we pass in [1,2,3] it will become 1,2,3 .

Demo

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store