Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
TypeScript Rest Parameters and Arguments
Next article icon

Rest Parameters in TypeScript

Last Updated : 22 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

  • Allow flexible and dynamic input handling in functions.
  • Simplify working with multiple arguments without specifying them individually.

Syntax

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

Parameters:

  • functionName: The name of your function.
  • ...rest: The rest parameter that collects all additional arguments into an array.
  • type[]: Specifies the type of elements in the rest array (e.g., number[], string[]).
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)); 
  • The sum function uses the rest parameter ...numbers to collect all arguments passed to it into an array of type number[].
  • The reduce method is applied to the numbers array, adding all its elements together to compute the total.

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)); 
  • The average function uses a rest parameter ...numbers to accept any number of numeric arguments.
  • It calculates the total sum of these numbers and returns their average.

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");  
  • The joinStrings function accepts multiple string arguments using a rest parameter.
  • It concatenates them into a single string, separated by commas.

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"); 
  • In this example, the rest parameter ...people is not placed at the end of the parameter list.
  • TypeScript requires rest parameters to be the last parameter; otherwise, a compiler error occurs.

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

  • Place Rest Parameters Last: Always define rest parameters at the end of the parameter list to ensure correct function behavior.
  • Use Appropriate Types: Specify the correct array type for rest parameters to maintain type safety and code clarity.
  • Limit to One Rest Parameter: A function should have only one rest parameter to avoid complexity and potential errors.
  • Avoid Overuse: Use rest parameters judiciously; overuse can lead to code that is hard to understand and maintain.

Next Article
TypeScript Rest Parameters and Arguments

S

sarahjane3102
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • TypeScript
  • JavaScript-Questions

Similar Reads

  • TypeScript Rest Parameters and Arguments
    TypeScript Rest Parameters allow functions to accept an indefinite number of arguments of the same type, collecting them into an array. Arguments refer to the actual values passed to a function when it's invoked, while Rest Parameters provide a way to handle multiple arguments as an array within the
    2 min read
  • TypeScript Rest Arguments
    TypeScript rest arguments use the spread operator (...) to capture a variable number of function arguments into an array. This allows for flexible operations like merging, concatenating, or processing multiple inputs dynamically within a single function. Syntaxfunction function_name(...rest: type[])
    2 min read
  • TypeScript Optional Parameters
    Optional parameters in TypeScript allow functions to be called without specifying all arguments, enhancing flexibility and code readability. Denoted by appending a ? to the parameter name.Optional parameters must follow the required parameters in function definitions.Syntaxfunction functionName(para
    3 min read
  • TypeScript Parameter Type Annotations
    TypeScript Parameter type annotations are used to specify the expected data types of function parameters. They provide a way to explicitly define the types of values that a function expects as arguments. Parameter type annotations are part of TypeScript's static typing system, and they help catch ty
    2 min read
  • Opaque Types In TypeScript
    In TypeScript Opaque types concept allows for the definition of specialized types such as strings or numbers which are derived from primitive types but do not have the characteristics of the base types, the purpose of this is to prevent specific actions regarding the type in question, or to make thi
    4 min read
  • Interfaces in TypeScript
    TypeScript is a statically typed superset of JavaScript that adds optional types, classes, interfaces, and other features to help developers build robust and maintainable applications. One of the most powerful features of TypeScript is interfaces, which allow you to define the structure of objects,
    4 min read
  • TypeScript Interfaces Type
    TypeScript Interfaces Type offers an alternative method for defining an object's type, allowing for a distinct naming approach. Syntax:interface InterfaceName { property1: type1; property2?: type2; readonly property3: type3; // ... method1(): returnType1; method2(): returnType2; // ...}Parameters:in
    2 min read
  • TypeScript Optional Properties Type
    TypeScript Opional properties type provides a way of defining the parts that are not necessarily required. TypeScript Optional Properties TypesOptional Properties are properties that are not required mandatorily and can be omitted when not needed.In TypeScript, you can define optional properties in
    6 min read
  • TypeScript Numbers
    TypeScript Numbers refer to the numerical data type in TypeScript, encompassing integers and floating-point values. The Number class in TypeScript provides methods and properties for manipulating these values, allowing for precise arithmetic operations and formatting, enhancing JavaScript's native n
    4 min read
  • Explain about rest parameters and arguments in TypeScript
    In this article, we will try to understand all the basic facts or details which are associated with Rest Parameters and Arguments in TypeScript. Rest Parameters: Rest Parameter allows us to accept zero or more arguments of the specified type.A function (or a method) has only one rest parameter.This
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences