`prefer-spread` incompatible with DOM APIs (and non-iterables)
See original GitHub issueQuoting https://github.com/sindresorhus/eslint-plugin-unicorn/issues/120#issuecomment-615220593:
unicorn/prefer-spread
is enabled by default as an error
when extending from unicorn:recommended
. I found a quite annoying edge-case, due to:
Array.from
works on Array-likes while...
only works on iterables.
It is true that:
Array-like is IMHO just a legacy quirk. Iterables is a better way to define things that can be iterated.
However, all DOM APIs (to my knowledge) don’t implement the [Symbol.iterator]
protocol.
// This works
for (const element of Array.from(document.querySelectorAll('.foo'))) {
console.log(element);
}
// This doesn't
for (const element of [...document.querySelectorAll('.foo')]) {
console.log(element);
}
I’ve enabled ESLint auto-fixing in my editor and more often than I’d like to admit I trolled myself with this pretty hard.
I’ll probably just demote the rule to be a warning, because I don’t want to monkey-patch the [Symbol.iterator]
protocol into the DOM API, even though that’d be even better, since then you could just do:
for (const element of document.querySelectorAll('.foo')) {
console.log(element);
}
I would recommend to make this rule a warning in unicorn:recommended
as well, to avoid this foot-gun.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:13 (4 by maintainers)
Top GitHub Comments
[...document.body.children]
works in all modern browsers now, including the latest version of Edge.https://stackoverflow.com/a/31574921/64949
Closing as this plugin only cares about modern browsers. If you need support for older browser you can simply disable the rule.
PR welcome if anyone cares enough to add a note to the rule docs about older browsers.
We can keep this open, because people still use something like
HTMLCollection
which can’t fix