166

I am running into an error that says

Type must have a '[Symbol.iterator]()' method that returns an iterator.

It hopes on the demarcated line:

class Test {
    private async do() {
        const done = [...(await this.test())]; // Here's the error
    }

    private async *test(): AsyncIterableIterator<string> {
        return;
    }
}

I have found a few issues in the TypeScript GitHub repository, but none seem to have helped. They all suggest adding new entries to lib. I am using es6 target and have added esnext, dom and es2018. This has had zero effect on the error.

Do I miss more lib entries (which I doubt as the ones I am using are the catchall ones with everything in) or is the code I am using invalid?

1
  • 3
    Doesn't look like the spread operator is supported for async iterables: relevant issue
    – jcalz
    Commented May 8, 2018 at 13:42

9 Answers 9

204

this has helped me. in tsconfig, add this :

{
    "compilerOptions": {
        "lib": [
            "es5", "es6", "dom", "dom.iterable"
        ]
    }
}

This is required for tsconfig to know which interfaces to import while transpiling your code.

dom.iterable includes all the interfaces mentioned here : https://github.com/microsoft/TypeScript/blob/main/src/lib/dom.iterable.d.ts

Also thanks to @domlas for mentioning this. I already upvoted his comment so that it is treated as default reason.

6
  • 4
    @IlyaEremin github.com/microsoft/TypeScript/blob/master/lib/…
    – domlas
    Commented Nov 7, 2019 at 14:50
  • 1
    I had to add tsconfig.json and tsconfig.base.json then it worked
    – Santosh
    Commented Jan 18, 2021 at 10:22
  • @Santosh you might be working in Angular or a similar library/framework. This is rather a framework-agnostic solution. Commented Jan 18, 2021 at 11:15
  • isn't "downlevelIteration": true, also needed duo to es5 support?
    – amirhe
    Commented Oct 22, 2021 at 18:01
  • 5
    You really only need "dom", "dom.iterable" but it works like a charm
    – JrBriones
    Commented Aug 8, 2022 at 18:18
39

I think you can get rid of the error if you cast "this.test()" to string or array.

My situation was different, but I think my solutions might help some fellow developers.

The error message I got was:

     Type 'Ingredient | Ingredient[]' must have a '[Symbol.iterator]()' 
     method that returns an iterator

enter image description here

I tried a few ways, and the following THREE worked, with the FIRST one as the simplest:

enter image description here

enter image description here

enter image description here

5
  • 3
    this is the most straightforward, relevant, and agnostic for others to find helpful. thank you!
    – Hugobop
    Commented Aug 1, 2023 at 21:17
  • If all you want to do is get rid of the error, just switch off Typescript... As soon as you need to use ... as ... in your code, it means that something is wrong in your code (unless you are very sure that you're just fixing something that typescript misunderstands). In your case, if action.payload ever is an Ingredient (non array), your code will now crash at runtime...
    – Claude
    Commented Apr 12 at 17:44
  • @Claude -- No. There is nothing wrong with that. Casting is a way that starts from college. w3schools.com/typescript/typescript_casting.php typescripttutorial.net/typescript-tutorial/type-casting Commented Apr 12 at 22:53
  • I'm not saying that casting cannot be handy at times (and the fact that it exists shows that). It's just that almost always casting means that something else in your code is wrong, and I do believe that the first instinct should be to fix that.
    – Claude
    Commented Apr 13 at 13:31
  • @Claude -- It's just your opinion. If "It's just that almost always casting means that something else in your code is wrong", casting should be illegitimate. But it's not. It's used in many cases. When we cast, it's educated cast. It's not that we cast anything anytime we want. For example, if you cast a number as an array, and then you use array methods on it, it just wouldn't work. But if an object is an array, but it doesn't say specifically, we can cast it to an array to get rid of the type error. Commented Apr 17 at 15:57
37

The error "Type Object must have a Symbol.iterator method that returns an iterator" occurs when we try to use the spread syntax (...) to unpack an object in an array. To solve the error, wrap your object in an array or correct your typings.

like this..

const obj = { name: 'James' };

// ⛔️ Error: Type Object must have a '[Symbol.iterator]()'
// method that returns an iterator.ts(2488)
const result = [...obj];

We tried to use the spread syntax to unpack the properties of an object directly into an array.

The solution for this depends on your use case. If you want to unpack the object into an array, wrap it in an array before using the spread syntax (...).

 const obj = { name: 'James' };

const result = [...[obj]];

console.log(result); // 👉️ [{name: 'James'}]

source here

3
34

As I commented above, the spread operator is unfortunately currently unsupported for asynchronous iterators. The relevant issue in GitHub is tc39/proposal-async-iteration#103.

Recap from that issue (minus extraneous stuff such as "you could do it this way, oops no you can't, never mind"):

@jedwards1211 said:

Will array spread operator support ever be part of this proposal?

@domenic ansered:

Not part of this proposal... Another proposal could certainly contemplate something new here.

And I don't see a proposal elsewhere (want to start one?). In any case, since it isn't part of even JavaScript ESNext, it most likely won't get added to TypeScript.

The most viable alternative is the for await syntax detailed in @estus's answer. Sorry I couldn't be more helpful. Good luck!

9

Despite what the syntax may suggest, async generator function isn't async function that returns a generator.

As the proposal states,

Async generator functions are similar to generator functions, with the following differences:

When called, async generator functions return an object, an async generator whose methods (next, throw, and return) return promises for { value, done }, instead of directly returning { value, done }. This automatically makes the returned async generator objects async iterators.

It returns asynchronous generator, not a promise, so awaiting it doesn't make any good.

Since asynchronous generator has Symbol.asyncIterator instead of Symbol.iterator, it's non-iterable iterator, i.e. it cannot be iterated with regular ES6 methods (Array.from, for..of, spread syntax, etc). This is the reason why for await..of was introduced.

The code above should be:

const values = [];

for await (const value of this.test()) {
  values.push(v);
}

The iteration over asynchronous iterator can be desugared similarly to regular iterators, the difference is that next() returns a promise of next value, not a value itself:

const iterator = this.test();
let next;
       
while ((next = await iterator.next()).done === false) {
  values.push(next.value);
}

Since asynchronous generator spec is a proposal, the support for async iterators in ES6 iteration methods may be subject to change.

1
  • 1
    Great answer, thank you, I was aware of for await but couldn't make sense of how to use that with the spread operator which @jcalz addressed so I'm inclined to accept their answer, however yours is really great too and I've upvoted it. Commented May 9, 2018 at 5:18
2

Simply tag as any[] to your spread operator e.g.

 addTemplateVariable(templateVariable: string) {
    this.patchState((state: CmsState) => ({
      cms: {
        ...state.cms,
        templateVariables: [
          ...state.cms.templateVariables as any[],
          templateVariable
        ]
      }
    }))
  }

I came across this problem when using ngrx component store

2

I encountered this error while trying to iterate over the values that were yielded by an async function*.

Changing from

for (const value of myAsyncGeneratorFunction()) {

to

for await (const value of myAsyncGeneratorFunction()) {

Fixed this error.

0

I had the same error trying to use the spread syntax (...) in a reducer(NgRx), you can see the following:

const _ingresoEgresoReducer = createReducer(initialState, 
    on(setItems, (state, { items }) => ({ ...state,  items: [...items]})), 
    on(unSetItems, state => ({ ...state,  items: []})), 
);

It shows the error "Type 'IngresoEgreso' must have a 'Symbol.iterator' method that returns an iterator." with the part [...items]

To solve the issue I should change to

const _ingresoEgresoReducer = createReducer(initialState, 
    on(setItems, (state, { items }) => ({ ...state,  items: [...[items]]})), 
    on(unSetItems, state => ({ ...state,  items: []})), 
);

And it works fine to me.

This solution was found at https://bobbyhadz.com/blog/typescript-type-object-must-have-symbol-iterator-method

-32

Error went if added

"strict": false

in tsconfig.json

1
  • 21
    They may not want to run with strict mode disabled.
    – gantoine
    Commented Jul 2, 2021 at 4:43

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.