2021-04-28 16:49:39 +02:00

33 lines
1.1 KiB
Plaintext

Functions that accept random numbers of arguments use a rest argument (``++... argname++``). This allows you to pass the function each relevant parameter individually. At runtime, those parameters are automatically wrapped in an array. If you pass an array to such a function, it will automatically be re-wrapped in another array, and this double-layering won't be expected by the called function. To avoid that double-layering, use the spread operator (``++...++``arrayToBeExpanded) in the call to expand the array.
This applies both to manually created arrays, and to arguments that were accepted as rest parameters.
== Noncompliant Code Example
----
collect(new Book(), new Book());
function collect(...books: Book[]) {
buy(books); // Noncompliant
}
function buy(...things: any[]) {
console.log(things); // outputs "[ [ Book {}, Book {} ] ]"
}
----
== Compliant Solution
----
collect(new Book(), new Book());
function collect(...books: Book[]) {
buy(...books);
}
function buy(...things: any[]) {
console.log(things); // outputs "[ Book {}, Book {} ]"
}
----