Last change
on this file since ceaed42 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
1.3 KB
|
Rev | Line | |
---|
[6a3a178] | 1 | /**
|
---|
| 2 | Get the element type of an `Iterable`/`AsyncIterable`. For example, an array or a generator.
|
---|
| 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 | function * iAmGenerator() {
|
---|
| 13 | yield 1;
|
---|
| 14 | yield 2;
|
---|
| 15 | }
|
---|
| 16 |
|
---|
| 17 | type MeNumber = IterableElement<ReturnType<typeof iAmGenerator>>
|
---|
| 18 | ```
|
---|
| 19 |
|
---|
| 20 | And here is an example with an async generator:
|
---|
| 21 |
|
---|
| 22 | @example
|
---|
| 23 | ```
|
---|
| 24 | async function * iAmGeneratorAsync() {
|
---|
| 25 | yield 'hi';
|
---|
| 26 | yield true;
|
---|
| 27 | }
|
---|
| 28 |
|
---|
| 29 | type MeStringOrBoolean = IterableElement<ReturnType<typeof iAmGeneratorAsync>>
|
---|
| 30 | ```
|
---|
| 31 |
|
---|
| 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.
|
---|
| 33 |
|
---|
| 34 | An example with an array of strings:
|
---|
| 35 |
|
---|
| 36 | @example
|
---|
| 37 | ```
|
---|
| 38 | type MeString = IterableElement<string[]>
|
---|
| 39 | ```
|
---|
| 40 | */
|
---|
| 41 | export type IterableElement<TargetIterable> =
|
---|
| 42 | TargetIterable extends Iterable<infer ElementType> ?
|
---|
| 43 | ElementType :
|
---|
| 44 | TargetIterable extends AsyncIterable<infer ElementType> ?
|
---|
| 45 | ElementType :
|
---|
| 46 | never;
|
---|
Note:
See
TracBrowser
for help on using the repository browser.