Capítulo 21 de 36
An object is iterable purely by implementing Symbol.iterator; for..of consumes that protocol to walk values (not keys), and the compiler's emitted code for it depends heavily on target — full native iterator support only kicks in at ES2015+.
Iterable<T> interface: the type to use when a parameter should accept anything implementing Symbol.iterator — arrays, Map, Set, strings, typed arrays all qualify natively. A generic function like toArray<X>(xs: Iterable<X>): X[] accepts any of them uniformly.for..of vs. for..in: for..of iterates values (via the object's Symbol.iterator); for..in iterates keys (as strings) and works on any object, not just iterables — it's an object-property-inspection tool, not a values-consumption tool. On an array, for..in yields index strings ("0", "1", ...) while for..of yields the actual elements. On a Set/Map, for..in only picks up enumerable own properties (e.g. a manually assigned extra property), while for..of yields the actual stored values via the iterator protocol.target:
for..of is only legal on Array-typed values (a compile error otherwise, even for objects that do implement Symbol.iterator) — the compiler downlevels it to a plain indexed for loop, since ES5 has no native iterator protocol to lean on.for..of loop directly, using the runtime's built-in iterator protocol — works for any iterable, not just arrays.const pets = new Set(["Cat", "Dog"]);
for (const p of pets) console.log(p); // "Cat", "Dog" — values via Symbol.iterator
for (const p in pets) console.log(p); // only enumerable own properties, not the Set's contents
for..of walking a Set's actual stored values through its iterator, versus for..in's unrelated key-enumeration behavior on the same object.for..of to consume values from anything iterable; reserve for..in for genuinely inspecting an object's own enumerable property names.for..of is restricted to arrays — check target before relying on it for Map/Set/custom iterables.Iterable<T> rather than a specific concrete type like T[].Symbol.iterator itself, the protocol this whole chapter is built on.Array<T>/Map<K,V>/Set<T> are all iterable generics.