61 lines
1.6 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
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
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
collect(new Book(), new Book());
function collect(...books: Book[]) {
buy(books); // Noncompliant
}
function buy(...things: any[]) {
console.log(things); // outputs "[ [ Book {}, Book {} ] ]"
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
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[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use spread operator '...' to pass this argument
'''
== Comments And Links
(visible only on this page)
=== on 3 Jan 2018, 20:37:24 Ann Campbell wrote:
\[~elena.vilchik] a little text on what "spread" is and why it's necessary (when the argument you're passing is apparently already an array) would be nice.
endif::env-github,rspecator-view[]