UNPKG

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