Borislav Hadzhiev
Thu Mar 03 2022·2 min read
Photo by Frank Mckenna
Use rest parameters to declare a function with variable number of arguments in
TypeScript, e.g. function myFunction(...args: string[]) {}
. Rest parameters
are used when a function takes an indefinite number of arguments. They appear
after all other parameters and use the ...
syntax.
// ✅ Example 1 (Named function) function getArgsAsArray(...args: string[]) { console.log(args); // 👉️ ['a', 'b', 'c'] return args; } console.log(getArgsAsArray('a', 'b', 'c')); // ✅ Example 2 (Arrow function) const multiply = (...numbers: number[]) => { console.log(numbers); return numbers.reduce((acc, curr) => acc * curr, 1); }; console.log(multiply(1, 2, 3, 4)); // 👉️ 24
We used rest parameters to declare functions that take a variable number of arguments.
...
syntax gathers the passed in arguments into an array.Notice that we typed the rest parameters as Type[]
and not Type
. This is
because the ...
syntax gather all the passed in parameters into an array.
When using rest parameters, make sure to explicitly type them, because otherwise
they will be implicitly typed as any[]
.
When using rest parameters, make sure they come last.
// 👇️ rest parameter must come last function getArgsAsArray(str: string, ...args: string[]) { console.log(str); // 👉️ "a" console.log(args); // 👉️ ['b', 'c'] return args; } console.log(getArgsAsArray('a', 'b', 'c'));
When using rest parameters, make sure to:
You can also use a type alias if your function declaration gets too busy.
type Multiply = (...numbers: number[]) => number; const multiply: Multiply = (...numbers) => { console.log(numbers); return numbers.reduce((acc, curr) => acc * curr, 1); }; console.log(multiply(1, 2, 3, 4)); // 👉️ 24
An easy way to think about rest parameters is:
Note that rest parameters are often confused with rest arguments.
Here is an example of using rest arguments.
// 👇️ this is rest parameter function logger(...args: string[]) { console.log(args); // 👉️ ['a', 'b', 'c'] } const arr = ['a', 'b', 'c']; // 👇️ this is rest argument logger(...arr);
Rest arguments use the ...
syntax as well, but are used when invoking a
function, and not when defining one.
The arr
variable is an array of strings, but the logger()
function takes
multiple, comma-separated strings, so we can't pass it an array of strings
directly.
This is why we used rest arguments - to unpack the values of the array in the
call to the logger()
function.