You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.3KB

  1. /**
  2. Get the element type of an `Iterable`/`AsyncIterable`. For example, an array or a generator.
  3. 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.
  4. This type works with both `Iterable`s and `AsyncIterable`s, so it can be use with synchronous and asynchronous generators.
  5. Here is an example of `IterableElement` in action with a generator function:
  6. @example
  7. ```
  8. function * iAmGenerator() {
  9. yield 1;
  10. yield 2;
  11. }
  12. type MeNumber = IterableElement<ReturnType<typeof iAmGenerator>>
  13. ```
  14. And here is an example with an async generator:
  15. @example
  16. ```
  17. async function * iAmGeneratorAsync() {
  18. yield 'hi';
  19. yield true;
  20. }
  21. type MeStringOrBoolean = IterableElement<ReturnType<typeof iAmGeneratorAsync>>
  22. ```
  23. 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.
  24. An example with an array of strings:
  25. @example
  26. ```
  27. type MeString = IterableElement<string[]>
  28. ```
  29. */
  30. export type IterableElement<TargetIterable> =
  31. TargetIterable extends Iterable<infer ElementType> ?
  32. ElementType :
  33. TargetIterable extends AsyncIterable<infer ElementType> ?
  34. ElementType :
  35. never;