My dilemma lies in a generator method I've created that asynchronously adds items to an array, and then yields each item using yield* array
at the end of the process. However, TypeScript compiler is throwing me off with an error message (TS2766) that I can't quite decipher. This error seems to imply something about the 'next' method of the iterator expecting type 'undefined' but receiving 'unknown'. How should I tackle this issue while still being able to yield the contents of the array?
TS2766: Cannot delegate iteration to value because the 'next' method of its iterator expects type 'undefined', but the containing generator will always send 'unknown'.
Edit: Here's the full code snippet for the problematic generator function:
/**
* Returns an iterator that loops over caught events
* @yields Promise<Event|CustomEvent>
*/
async *on(eventName: string, options?: AddEventListenerOptions): AsyncGenerator<Event> {
if (this.#eventsListened.has(eventName)) {
return;
}
let results: Event[] = [];
let resolve: (value?: PromiseLike<Event> | Event) => void;
let promise = new Promise<Event>(r => (resolve = r));
let done = false;
this.#eventsListened.add(eventName);
if (typeof options === 'object' && typeof options.once !== 'undefined') {
throw new Error('options.once is not supported. Use EventTarget2.once instead');
}
const callback = (evt: Event) => {
results.push(evt);
resolve();
promise = new Promise<Event>(r => (resolve = r));
};
this.addEventListener('eventName', callback, options);
while (!done) {
await promise;
yield* results;
results = [];
done = !this.#eventsListened.has(eventName);
}
this.removeEventListener(eventName, callback);
}