Rest parameter is written after all the other parameters in a function and uses the ... (three-dot syntax) syntax. The rest parameter is an array and should have an associated type associated with the array in Typescript.
TL;DR
// Function that says greeting to all the peoples
function sayGreetingToPeoples(greeting: string, ...peoples: string[]) {
peoples.forEach((people) => {
console.log(`${greeting} ${people}`);
});
}
// call the function
sayGreetingToPeoples("Hi, ", "Roy", "John", "Lily");
/*
OUTPUT
------
Hi, Roy
Hi, John
Hi, Lily
*/
For example, let's say we have a function called sayGreetingToPeoples, where the first parameter is the greeting to say to the people and the second parameter is a rest parameter and is considered as the names of the people that need to be greeted.
It can be done like this,
// says greeting to all the peoples
function sayGreetingToPeoples(greeting, ...peoples) {
// cool code here
}
Now let's assign the type of string to the greeting parameter and the type of string[] to the peoples rest parameter.
The peoples parameter is a rest parameter and will always be an array type and since we need it to be a string array we are using the string[] syntax.
It can be done like this,
// says greeting to all the peoples
function sayGreetingToPeoples(greeting: string, ...peoples: string[]) {
// cool code here
}
Let's write the logic for the function inside the function body to greet all the people using a loop.
It can be done like this,
// says greeting to all the peoples
function sayGreetingToPeoples(greeting: string, ...peoples: string[]) {
peoples.forEach((people) => {
console.log(`${greeting} ${people}`);
});
}
Lastly, let's call the sayGreetingToPeoples function like this,
// says greeting to all the peoples
function sayGreetingToPeoples(greeting: string, ...peoples: string[]) {
peoples.forEach((people) => {
console.log(`${greeting} ${people}`);
});
}
// call the function
sayGreetingToPeoples("Hi, ", "Roy", "John", "Lily");
/*
OUTPUT
------
Hi, Roy
Hi, John
Hi, Lily
*/
See the above code live in codesandbox.
That's all 😃!