Last updated: Feb 27, 2024
Reading timeยท3 min
Use rest parameters to declare a function with a variable number of arguments in TypeScript.
Rest parameters are used when a function takes an indefinite number of
arguments. They appear after all other parameters and use the ...
syntax.
function getArgsAsArray(...args: string[]) { console.log(args); // ๐๏ธ ['a', 'b', 'c'] return args; } console.log(getArgsAsArray('a', 'b', 'c'));
Here is another example.
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 the rest parameters syntax 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 gathers 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 the rest parameters syntax is:
Note that rest parameters are often confused with rest arguments.
Here is an example of using rest arguments.
// ๐๏ธ this is rest parameters function logger(...args: string[]) { console.log(args); // ๐๏ธ ['a', 'b', 'c'] } const arr = ['a', 'b', 'c']; // ๐๏ธ this is rest arguments logger(...arr);
Rest arguments use the ...
syntax as well but are used when calling 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.
If you need to pass a function as a parameter, check out the following article.
You can learn more about the related topics by checking out the following tutorials: