JS/TS Filter On AsyncIterable<T>

Viewed 25

I have a variable of type AsyncIterable. I want to filter on it, for example (psuedo code below) -

class SomeClass {
    private SOME_CONST= "ABCDE";

    private async someFunction(): Promise<string> {
        const items: AsyncIterable<string> = await someLibrary.getAsyncItems(); // this library's function returns type of AsyncIterable<T>

        return items.filter(item => item === this.SOME_CONST);
    }
}

How can I filter on AsyncIterable? I get the error - "Property 'filter' does not exist on type 'AsyncIterable'

1 Answers

You can't filter on a synchronous iterator either, you'll need to it convert it to an array.

At the moment there is no method like Array.from() for AsyncIterable (pending proposal) but you can do following :

async function toArray<T>(asyncIterator: AsyncIterable<T>) {
  const arr = [];
  for await (const i of asyncIterator) arr.push(i);
  return arr;
}

then you can do

declare const items: AsyncIterable<string>;

async function foo() {
  (await toArray(items)).filter(() => true)
}

Playground

Related