Typescript rest parameters
Created By: chatGPT
Rest parameters allow us to pass a variable number of arguments to a function. Instead of defining multiple parameters explicitly, we can use a single parameter prefixed with
...
to handle any number of arguments as an array.function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
const total = sum(1, 2, 3, 4, 5);
console.log(total); // Output: 15
In the example above, the
sum
function uses rest parameters to collect all arguments into the numbers
array. The reduce
method is then used to compute the total.function concatenateStrings(...strings: string[]): string {
return strings.join(' ');
}
const result = concatenateStrings('Hello', 'World', 'from', 'TypeScript');
console.log(result); // Output: Hello World from TypeScript
We can also combine rest parameters with other parameters. For instance, we can accept a fixed set of parameters before the rest parameter.
function greet(greeting: string, ...names: string[]): string {
return `${greeting}, ${names.join(', ')}!`;
}
const greetingMessage = greet('Hello', 'Alice', 'Bob', 'Charlie');
console.log(greetingMessage); // Output: Hello, Alice, Bob, Charlie!
It's important to remember that rest parameters must be the last parameter in a function's parameter list. You can't place other parameters after it.
function invalidFunction(...args: any[], lastArg: number) {
// This will throw an error
}
// Correct usage
function validFunction(lastArg: number, ...args: any[]) {
// This is valid
}
In summary, rest parameters provide a flexible way to work with a variable number of arguments in TypeScript, enhancing the expressiveness of your functions.
const numbersOnly = sum(10, 20, 30);
const mixedParams = concatenateStrings('Data', 'Types', 'in', 'JavaScript', 'and', 'TypeScript');