Using Rest Parameters in TypeScript Functions

Last updated on November 17, 2021 A Goodman Loading... Post a comment

In TypeScript, you can use the spread operator (…) as the final parameter of a function. All of the arguments (except the ones that were explicitly declared before the three dots) passed to that function will be taken and placed in an array.

Words may be confusing and non-intuitive. The example below will make things much clearer.

Example:

const example = (name: string, age: number, ...skills: string[]): void => {
  console.log(`Hello ${name}`);
  console.log(`You are ${age} years old`);
  skills.map(skill => {
    console.log(`You can code in ${skill}`)
  })
}

// Invoke the function
example('John Doe', 41, 'Javascript', 'PHP', 'C', 'Java');

Output:

Hello John Doe
You are 41 years old
You can code in Javascript
You can code in PHP
You can code in C
You can code in Java

Further reading:

You can also check out our TypeScript category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like