2 Get the element type of an `Iterable`/`AsyncIterable`. For example, an array or a generator.
4 This can be useful, for example, if you want to get the type that is yielded in a generator function. Often the return type of those functions are not specified.
6 This type works with both `Iterable`s and `AsyncIterable`s, so it can be use with synchronous and asynchronous generators.
8 Here is an example of `IterableElement` in action with a generator function:
12 function * iAmGenerator() {
17 type MeNumber = IterableElement<ReturnType<typeof iAmGenerator>>
20 And here is an example with an async generator:
24 async function * iAmGeneratorAsync() {
29 type MeStringOrBoolean = IterableElement<ReturnType<typeof iAmGeneratorAsync>>
32 Many types in JavaScript/TypeScript are iterables. This type works on all types that implement those interfaces. For example, `Array`, `Set`, `Map`, `stream.Readable`, etc.
34 An example with an array of strings:
38 type MeString = IterableElement<string[]>
41 export type IterableElement<TargetIterable> =
42 TargetIterable extends Iterable<infer ElementType> ?
44 TargetIterable extends AsyncIterable<infer ElementType> ?