44 lines
1.2 KiB
Plaintext
44 lines
1.2 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 {} ]"
|
|
}
|
|
----
|
|
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|