Advertisement
Intermediate TypeScript, Function Types, Overloads & Optional/Default Parameters

How do rest parameters work with type annotations, and what type must the annotation be?

Short answer

A rest parameter (prefixed with '...') collects any remaining arguments into an array, so its type annotation must be an array type (or tuple type for fixed-shape variadic arguments), matching how rest parameters behave in plain JavaScript.

Save TypeScript mock interview
Advertisement
AModel answer
A rest parameter (prefixed with '...') collects any remaining arguments into an array, so its type annotation must be an array type (or tuple type for fixed-shape variadic arguments), matching how rest parameters behave in plain JavaScript.
function sum(...nums: number[]): number {
  return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6
Real-world example
Typing a logging function that accepts a variable number of arguments of the same type.
Likely follow-ups
  • Can you type a rest parameter as a tuple to enforce a fixed minimum number of arguments?
Related topics