Collection-agnostic APIs
A utility needs to consume arrays, sets, maps, strings, or typed arrays through one parameter.
TypeScript · Interface
Iterable<T> describes values that implement Symbol.iterator and yield elements of type T. It lets functions accept arrays and other iterable collections through one generic type.
Iterable<T> describes a value whose [Symbol.iterator]() method produces values of type T. It lets APIs accept arrays and other iterable built-ins uniformly, while operations such as spread and for...of consume the iterable's yielded values.
Iterable<T>| Name | Type | Description |
|---|---|---|
T | type parameter | The element type yielded by the iterable. |
An iterable value yields elements of type T; the page's example converts those elements to T[].
Symbol.iterator implementation.Iterable<T> when an API should accept a broad family of iterable inputs.for...of loop starts iteration through the object's symbol-keyed iterator method.for...of is value-oriented, unlike key-oriented property enumeration.for...of over non-array iterables is rejected even when those values implement Symbol.iterator; use an appropriate target or iteration configuration.function toArray<T>(items: Iterable<T>): T[] {
return [...items];
}
const values = toArray(new Set([1, 2, 3]));
console.log(values);The function accepts any iterable and materializes its yielded values into a typed array.
A utility needs to consume arrays, sets, maps, strings, or typed arrays through one parameter.
A function materializes any iterable into a new array with its element type preserved.
A loop should consume yielded values rather than object property names.
Iterable<T> mean in TypeScript?Iterable<T> represents a value that can be iterated and yields elements of type T. Arrays, maps, sets, strings, and several typed arrays provide the required Symbol.iterator implementation.
Follow-up: How does for...of differ from for...in? for...of reads iterable values, whereas for...in enumerates property keys.
The iterable protocol is based on a Symbol.iterator property whose function returns the sequence's iterator. A generic parameter records the type of each value produced by that sequence.
Follow-up: What does the iterator method itself return? It returns the iterator used to obtain the values being traversed.
Iterable<T> in a public API?A function parameter typed as Iterable<T> can accept different iterable collections without requiring an array specifically. For example, spreading the parameter into an array preserves the element type as T.
Follow-up: Why might a library prefer this parameter type? It supports the minimal protocol needed by consumers and avoids unnecessarily restricting callers to one collection representation.
IteratorIterableIteratorGeneratorSymbol.iteratorfor...of