I can implement my own generator function which returns a Generator. The type for this can be defined as type Iterable = { [Symbol.iterator](): Generator };
, but this isn't valid for built-in types like Array. Probably because they're designed to iterate multiple times instead of just once.
Reading the docs on Array, it says this method returns "new array iterator object" which links to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol
type IterableBuiltIn = { [Symbol.iterator](): { next: any, value: any, return: any };
const array: IterableBuiltIn = [1, 2, 3];
for (const value in array) {
console.log(value);
}
CodePudding user response:
To not get a type error, we need to at least define the type as type Iterator = { [Symbol.iterator](): { next: any, value: any, return: any };
, but this is more thorough as per the spec according to the docs.
type IteratorResult = { done?: boolean, value?: any };
type Iterator = {
[Symbol.iterator](): {
next(arg?: any): IteratorResult,
return?(arg?: any): IteratorResult,
throw?(error?: any): IteratorResult
}
};
CodePudding user response:
Better yet, just noticed, this is defined in es2015.iterable. Meaning with the right tsconfig, this is defined for you.