1 | /**
|
2 | Get the element type of an `Iterable`/`AsyncIterable`. For example, `Array`, `Set`, `Map`, generator, stream, etc.
|
3 |
|
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.
|
5 |
|
6 | This type works with both `Iterable`s and `AsyncIterable`s, so it can be use with synchronous and asynchronous generators.
|
7 |
|
8 | Here is an example of `IterableElement` in action with a generator function:
|
9 |
|
10 | @example
|
11 | ```
|
12 | import type {IterableElement} from 'type-fest';
|
13 |
|
14 | function * iAmGenerator() {
|
15 | yield 1;
|
16 | yield 2;
|
17 | }
|
18 |
|
19 | type MeNumber = IterableElement<ReturnType<typeof iAmGenerator>>
|
20 | ```
|
21 |
|
22 | And here is an example with an async generator:
|
23 |
|
24 | @example
|
25 | ```
|
26 | import type {IterableElement} from 'type-fest';
|
27 |
|
28 | async function * iAmGeneratorAsync() {
|
29 | yield 'hi';
|
30 | yield true;
|
31 | }
|
32 |
|
33 | type MeStringOrBoolean = IterableElement<ReturnType<typeof iAmGeneratorAsync>>
|
34 | ```
|
35 |
|
36 | Many types in JavaScript/TypeScript are iterables. This type works on all types that implement those interfaces.
|
37 |
|
38 | An example with an array of strings:
|
39 |
|
40 | @example
|
41 | ```
|
42 | import type {IterableElement} from 'type-fest';
|
43 |
|
44 | type MeString = IterableElement<string[]>
|
45 | ```
|
46 |
|
47 | @example
|
48 | ```
|
49 | import type {IterableElement} from 'type-fest';
|
50 |
|
51 | const fruits = new Set(['🍎', '🍌', '🍉'] as const);
|
52 |
|
53 | type Fruit = IterableElement<typeof fruits>;
|
54 | //=> '🍎' | '🍌' | '🍉'
|
55 | ```
|
56 |
|
57 | @category Iterable
|
58 | */
|
59 | export type IterableElement<TargetIterable> =
|
60 | TargetIterable extends Iterable<infer ElementType> ?
|
61 | ElementType :
|
62 | TargetIterable extends AsyncIterable<infer ElementType> ?
|
63 | ElementType :
|
64 | never;
|