2

I am trying out the "new" async generator/for dance:

async function* it() {
    yield "Hello";
    yield "World";
}

async function test() {
    for await (const x of it()) {
        console.log()
    }
}

I am getting the following error:

error TS2504: Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator.

How can I make work?

What's the right "typesafe" return type for the "it" function?

2 Answers 2

5

Your code is actually fine, but async iterators are currently an ES.next feature, so you'll have to specify this ES version, e.g. by putting the following property in your tsconfig.json:

"target": "esnext"

Transpiling

If you want to transpile to a previous ES version, TypeScript will not handle this for you automatically. Instead, you can use core-js:

First, install core-js: npm install core-js

Then, edit tsconfig.json:

{
  compilerOptions: {
    "lib": [
      "es2015",
      "esnext.asynciterable"
    ],
    "target": "es2015"
    [...]
  },
  [...]
}

Then, import core-js in to your source file:

import 'core-js/shim';
Sign up to request clarification or add additional context in comments.

4 Comments

1. Now do I make the iterator typesafe? 2. Can I transpill to older targets?
TypeScript should infer the type of the it function automatically. I added information for transpiling to my answer.
I still need a type since I want to generate an interface function*. Like “interface I { queryAll() : ???<string> }.
GOT IT WORKING! Remarks: - it must be npm i core-js (not corejs) - AsyncIterableIterator<T> is the return type of function*
-2

You need to shim asyncIterator Symbol.

(Symbol as any).asyncIterator = Symbol.asyncIterator || Symbol.for('Symbol.asyncIterator');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.