Working With TypeScript Rest Parameters

24 Jun 2023 Balmiki Mandal 0 Typescript

Working with TypeScript Rest Parameters

TypeScript is a powerful language that allows you to write robust, well-structured code. It also provides support for rest parameters, which are parameters in a function that allow you to collect an arbitrary number of arguments into an array. In this article, we’ll explore how to use rest parameters in TypeScript and some of the different ways that they can be used.

What are Rest Parameters?

Rest parameters are parameters that appear after the “normal” (aka required) parameters in a function. They consist of a set of named parameters followed by a set of unnamed parameters. All unnamed parameters are then put into an array. Rest parameters are especially useful when the number of parameters you’re dealing with is not known ahead of time.

Declaring Your Function with Rest Parameters

You declare your rest parameters by putting three dots (…) before a parameter. In the example below, the totalPrice parameter will be the rest parameter. All the parameters passed after totalPrice will be collected into an array and assigned to the totalPrice variable.


function calculatePrice(name: string, quantity: number, ...totalPrice: number[]): number {
    // code here
    return totalPrice.reduce((a,b) => a + b, 0);
}

Using Rest Parameters

Now that we’ve declared our function with a rest parameter, we can use it in any number of situations. We can loop through the array, apply methods to it, or even pass it into another function.


// Loop through the parameters
let total = calculatePrice("Pizza", 2, 5.50, 3.50, 4.00);
totalPrice.forEach((price) => {
    console.log(price);
});

// Apply methods to the array
let sortedPrices = totalPrice.sort();
console.log(sortedPrices);

// Pass it into another function
let sum = addPrices(totalPrice);

function addPrices(prices: number[]): number {
    return prices.reduce((a,b) => a + b, 0);
}

Conclusion

In this article, we looked at how to use rest parameters in TypeScript. Rest parameters are great for working with unknown numbers of arguments in a function and can make your code more concise and easier to work with.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.