A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/typescript/rest-parameters-in-typescript/ below:

Rest Parameters in TypeScript - GeeksforGeeks

Rest Parameters in TypeScript

Last Updated : 22 Jan, 2025

Rest parameters in TypeScript enable functions to handle an unlimited number of arguments by grouping them into an array. They are defined using ... and must be the last parameter.

Syntax
function function_name(...rest: type[]) {
// Type of the is the type of the array.
}

Parameters:

JavaScript
function sum(...numbers: number[]): number {
  return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3));
console.log(sum(10, 20));

Output:

6
30
Calculating the Average of Numbers TypeScript
function average(...numbers: number[]): number {
    let total = 0;
    for (let num of numbers) {
        total += num;
    }
    return numbers.length === 0 ? 0 : total / numbers.length;
}

console.log("Average of the given numbers is:", average(10, 20, 30, 60));
console.log("Average of the given numbers is:", average(5, 6));
console.log("Average of the given numbers is:", average(4));

Output:

Average of the given numbers is : 30
Average of the given numbers is : 5.5
Average of the given numbers is : 4
Concatenating Strings TypeScript
function joinStrings(...strings: string[]): string {
    return strings.join(', ');
}

console.log(joinStrings("rachel", "john", "peter") + " are mathematicians");
console.log(joinStrings("sarah", "joseph") + " are coders"); 

Output:

rachel, john, peter are mathematicians
sarah, joseph are coders
Incorrect Usage of Rest Parameters TypeScript
// Incorrect usage - will raise a compiler error
function job(...people: string[], jobTitle: string): void {
  console.log(`${people.join(', ')} are ${jobTitle}`);
}

// Uncommenting the below line will cause a compiler error
// job("rachel", "john", "peter", "mathematicians");

Output: Typescript compiler raised the error.

main.ts(2,14): error TS1014: A rest parameter must be last in a parameter list.      
Best Practices for Using TypeScript Rest Parameters

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4