UNPKG

1.46 kBTypeScriptView Raw
1/**
2Get the element type of an `Iterable`/`AsyncIterable`. For example, an array or a generator.
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. For example, `Array`, `Set`, `Map`, `stream.Readable`, etc.
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@category Iterable
48*/
49export type IterableElement<TargetIterable> =
50 TargetIterable extends Iterable<infer ElementType> ?
51 ElementType :
52 TargetIterable extends AsyncIterable<infer ElementType> ?
53 ElementType :
54 never;