Thursday, November 8, 2018

TypeScript - ES6 - rest and spread operators

The Rest and the spread operators are some new additions in TypeScript 2.1. These operators help us to work with arrays and list of numbers.

SPREAD operator:

Arrays are numbers separated by commas within square brackets. But, to functions like Math.max() and Math.min() - the input required is a list of numbers. Consider the following example:

// reset and spread operator usage
const myNumberSet = [1,10,99,-5];
console.log(Math.min(33,99,10,-3));
console.log(Math.min(...myNumberSet));

Since, we have an array and we want to convert it to a list of numbers so that we can provide it as an input to the function Math.min(). We can prepend 3 dots to the arrayName. This is called the spread operator. This is what we have used in the below:
console.log(Math.min(...myNumberSet));

Spread opearator is very useful as it allows us to flexibly transform the arrays without writing any complicated loops.

REST Operator:

If we want to convert a list of numbers to a number array - we can use the REST operator in the function input argument as follows.

function change2Array(...inputArgs:number[]){
return inputArgs;
};

console.log(change2Array(1,2,3,4,5,6,7,8,9));


Really, the difference, between REST and SPREAD operator is the location of the usage.


Reference:

No comments:

Post a Comment