After replacing a list with a wrapper class that allows for monitoring changes to the list, I noticed that I can no longer use the forEach
statement to iterate over the class.
let numberList = new EventList<number>([1,2,3,4]);
numerList.forEach((element: number) => console.log(element));
An error message is displayed stating:
Property 'forEach' does not exist on type 'EventList<number>'.
I expected the EventList
class to have the forEach
function implicitly since it implements the Iterable
interface.
This is the implementation of the EventList<T>
class:
export class EventList<T> implements Iterable<T>{
private list: T[] = [];
private changeListener: ((list: T[]) => void)[] = [];
constructor(items: T[] = []) {
this.list = items;
}
public push(element: T): void {
this.list.push(element);
this.emitChange();
}
public splice(index: number, deletCount?: number) {
this.list.splice(index, deletCount);
this.emitChange();
}
public onChange(callback: (list: T[]) => void) {
this.changeListener.push(callback);
}
[Symbol.iterator](): Iterator<T> {
let currIndex = 0;
const items = this.list;
return {
next(): IteratorResult<T> {
if(currIndex < items.length) {
return { done: false, value: items[currIndex++] };
} else {
return { done: true, value: null };
}
}
};
}
private emitChange(): void {
for (const listener of this.changeListener) {
listener(this.list);
}
}
}