Home > Net >  '[Symbol.iterator]()' method that returns an iterator
'[Symbol.iterator]()' method that returns an iterator

Time:01-18

I'm facing this error in my code when using strict mode and I'm not managing it.

"message": "Type 'MyType<string>[] | undefined' must have a '[Symbol.iterator]()' method 

It is happenning in this line of code:

const [optionAll, ...options] = await service.getLineOfBusiness().toPromise();

this service method returns an observable of a list of MyType:

public getLineOfBusiness(): Observable<MyType<string>[]> 

This MyType is quite simple interface:

export interface MyType<T = unknown> {
   key: string;
   value: T;
   extra?: string;
}

How can I solve it?

CodePudding user response:

MyType<string>[] can be destructured with array-like syntax but undefined cannot.

If you are sure that getLineOfBusiness() will always return an array in this specific usage (and not undefined), you could add a non-null assertion (!) to the awaited expression to suppress the error:

const [optionAll, ...options] = (await service.getLineOfBusiness().toPromise())!;
  • Related