Rest parameters with types in Typescript - Time & Space Complexity
Let's see how the time needed to run a function changes when it uses rest parameters with types.
We want to know how the number of inputs affects the work done inside the function.
Analyze the time complexity of the following code snippet.
function sumAll(...numbers: number[]): number {
let total = 0;
for (const num of numbers) {
total += num;
}
return total;
}
This function adds up all numbers passed to it using rest parameters typed as an array of numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the rest parameter array.
- How many times: Once for each number passed to the function.
As you add more numbers, the function does more additions, one for each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of inputs.
Time Complexity: O(n)
This means the time to finish grows in a straight line as you add more numbers.
[X] Wrong: "Rest parameters make the function run instantly no matter how many inputs there are."
[OK] Correct: Even though rest parameters collect inputs nicely, the function still needs to look at each input once to add them up.
Understanding how rest parameters affect time helps you explain how your functions handle many inputs clearly and confidently.
"What if we changed the function to multiply all numbers instead of adding? How would the time complexity change?"