乐闻世界logo
搜索文章和话题

What is the rest parameter in TypeScript?

1个答案

1

In TypeScript, rest parameters are a syntax feature for functions that allows you to pass any number of arguments. Represented by three dots (...), it enables you to pass an arbitrary number of arguments as an array to the function.

One of the main advantages of using rest parameters is that it provides a highly flexible way to handle function inputs, especially when you are unsure about the number of arguments that will be received. This is particularly useful when working with lists or other variable-length data structures.

For example, suppose we need to write a function that accepts any number of numbers and returns their sum. Using rest parameters, we can implement it as follows:

typescript
function sum(...numbers: number[]): number { return numbers.reduce((acc, current) => acc + current, 0); } console.log(sum(1, 2, 3)); // Output 6 console.log(sum(10, 20, 30, 40, 50)); // Output 150

In this example, the sum function uses ...numbers as a parameter, which collects all incoming arguments into an array named numbers. Then, we use the reduce method to iterate through the array and compute the sum.

This flexibility proves valuable in many real-world scenarios, such as processing input data of varying formats or passing parameters to parent classes in constructors.

2024年8月2日 13:44 回复

你的答案