Typing Rest Parameters
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 27 of 73.
TypeScript provides rest parameters to handle this scenario elegantly while maintaining type safety.
Rest parameters use the spread operator (...) followed by a parameter name and a typed array. This collects all remaining arguments into a single array parameter:
function sum(...numbers: number[]): number {
let total = 0;
for (const num of numbers) {
total += num;
}
return total;
}
// Can be called with any number of arguments
sum(1, 2); // 3
sum(1, 2, 3, 4, 5); // 15The rest parameter must always be the last parameter in the function signature. TypeScript ensures that all arguments passed to the rest parameter match the specified array type, giving you the flexibility of variable arguments with the safety of static typing.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a function named sumAll that uses rest parameters to accept any number of numeric arguments and returns their sum as a number. The function should have an explicit return type annotation.
Create another function named findMaximum that uses rest parameters to accept any number of numeric arguments and returns the largest value among them as a number. The function should have an explicit return type annotation.
Create a third function named concatenateStrings that takes a required separator parameter of type string, followed by rest parameters that accept any number of string arguments. The function should return all the string arguments joined together with the separator between them. The function should have an explicit return type annotation of string.
Test your functions by calling them with the following values and printing the results:
- Call
sumAllwith5,10, and15 - Call
sumAllwith1,2,3,4, and5 - Call
findMaximumwith8,3,12, and7 - Call
findMaximumwith25and18 - Call
concatenateStringswith"-"as separator and"apple","banana","cherry" - Call
concatenateStringswith" | "as separator and"red","green","blue","yellow"
Print each result on a separate line in the order specified above.
Cheat sheet
Rest parameters use the spread operator (...) to collect remaining arguments into a typed array:
function sum(...numbers: number[]): number {
let total = 0;
for (const num of numbers) {
total += num;
}
return total;
}
// Can be called with any number of arguments
sum(1, 2); // 3
sum(1, 2, 3, 4, 5); // 15The rest parameter must always be the last parameter in the function signature. You can combine regular parameters with rest parameters:
function concatenate(separator: string, ...strings: string[]): string {
return strings.join(separator);
}Try it yourself
// TODO: Write your code here
// Create the sumAll function with rest parameters
// Create the findMaximum function with rest parameters
// Create the concatenateStrings function with separator and rest parameters
// Test the functions and print results
console.log(sumAll(5, 10, 15));
console.log(sumAll(1, 2, 3, 4, 5));
console.log(findMaximum(8, 3, 12, 7));
console.log(findMaximum(25, 18));
console.log(concatenateStrings("-", "apple", "banana", "cherry"));
console.log(concatenateStrings(" | ", "red", "green", "blue", "yellow"));This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples