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