Utilize the forEach method with a TypeScript wrapper class containing a list

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);
        }
    }
}

Answer №1

It seems like the forEach method is not native to the iterable object, so you'll need to create your own implementation for it.

forEach(callback: (item: T) => void) {
  for (const item of this) {
    callback(item);
  }
}

Answer №2

, it is necessary to specify the forEach method in the EventList class since it does not inherit directly from Array. To accomplish this, you must include the following function:
public forEach(callback: (element: T) => void): void {
     this.list.forEach(callback);
}

Answer №3

ForEach is not automatically implemented by Iterable.

The correct signature should be as follows:

forEach(callback: (value: T, index: number, element: T[]) => void): void {
    this.list.forEach(callback);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting up the environment for Angular 7 within a TFS build pipeline

I've been attempting to customize the environment in my tfs build pipeline, but it keeps defaulting to the dev environment. Oddly enough, the 'ng serve' command is working perfectly fine. Below are the version details of my application: An ...

Effortlessly apply mapping, filtering, reducing, and more in JavaScript

Array#map and Array#filter both create a new array, effectively iterating over the original array each time. In languages like rust, python, java, c#, etc., such expression chains only iterate once, making them more efficient in certain cases. While this ...

Python: Reiterate through a List

Here is the list I have: myList = [42,28,14,28,14,28,42,14] I am using this list to create a longer version based on the sequence above. My goal is to iterate through the list and continue iterating until a certain condition is met. Thank you for your r ...

TypeScript Redux Thunk: Simplifying State Management

Seeking a deeper understanding of the ThunkDispatch function in TypeScript while working with Redux and thunk. Here is some code I found: // Example of using redux-thunk import { Middleware, Action, AnyAction } from "redux"; export interface ThunkDispatc ...

Two distinct arrays interacting and syncing with each other through a single API request

I find myself in a strange situation. I am dealing with two objects: sessionBase: ISessionViewWrapperModel = <ISessionViewWrapperModel>{}; sessionDisplay: ISessionViewWrapperModel = <ISessionViewWrapperModel>{}; After making an api call, both ...

Is it required to double click checkboxes to uncheck them?

My checkboxes require 2 clicks to be unchecked, even though one click is enough to check them. This issue occurs in all 7 checkboxes and there is no onchange() function or similar in TS. import { Component, OnInit, Inject } from '@angular/core&apos ...

Alert: The route "/D:/original/22-02-2017/job2.html" specified in [react-router] does not correspond to any existing routes

I am currently working on a project using TypeScript with React. I'm utilizing webpack as a compiler, and my directory structure looks like this: d:/original/22-02-2017/ - In my web.config.js file, the entry point is set to ./src/index.tsx. All ...

Invoking a function from a collection of mixed data types

I have established a mapping for a discriminated union consisting of different types, each linked to a corresponding function that uses a member of the union as a parameter: export interface Truncate { type: 'truncate' maxLength: number } ex ...

Any idea how to resolve this typescript typing issue: "The argument, either a string or number, cannot be assigned to the parameter of type 'SetStateAction<string>'"?

Just recently delving into TypeScript, I've encountered a persistent typing problem that has proven challenging to resolve despite numerous attempts. The error message causing me trouble reads as follows: Argument of type 'string | number' ...

Issues with implementing Firebase Phone Authentication in Ionic 3

When trying to authenticate a phone number in Ionic 3 using Firebase, the program runs without error. However, after entering the phone number, nothing happens... The .html code is shown below: <ion-item> <ion-label stacked>Phone Number</i ...

Using Angular 4 to pass a specific array element from the parent component to the child component and showcasing its value in the child's HTML

I am currently working on an Angular 4 application and in need of passing an array called NpvResults from the parent component to a child component. The goal is to access this array within the child component and display its value to the client of the chil ...

Type of event target MouseEvent

I am currently working on a custom hook const hasIgnoredClass = (element: Element, ignoredClass: string) => (element.correspondingElement ? element.correspondingElement : element ).classList.contains(ignoredClass); const isInIgnoredElement = ( ...

Customize React Hook Form version 7 by incorporating a unique input method for handling empty values

Introducing my custom Input component: export type InputProps = { error?: string } & InputHTMLAttributes<HTMLInputElement> export const Input: FunctionComponent<InputProps> = ({ error, ...props }) => ( <input {...props} /> ) ...

Issues with the 'GET' request functionality on the deployed Angular project

I am attempting to run an Angular project that I have built. After copying the folder generated from 'ng build' and placing it in the directory where my back end code (using express) is located, I am trying to run it on my laptop at port 3000. Wh ...

Encountering an error while implementing a Typescript addEventListener for keydown events

Struggling with adding and removing event listeners to HTML elements capable of focus, such as buttons. encountering a typescript error specifically related to the lines of code responsible for adding and removing the event listener: focusableElements.fo ...

Removing fields when extending an interface in TypeScript

Attempting to extend the ISampleB interface and exclude certain values, like in the code snippet below. Not sure if there is an error in this implementation export interface ISampleA extends Omit<ISampleB, 'fieldA' | 'fieldB' | &apos ...

"Angular application experiencing navigation blockage due to multiple concurrent HTTP requests using RxJS - Implementation of priority-based cancel queue

I've come across similar threads, but I have yet to find a suitable solution for my specific issue. Situation: Currently, I'm navigating on both the server side and client side simultaneously. This entails that every frontend navigation using ro ...

next-intl failing to identify the primary language setting

When testing next-intl for the app directory in the Next.js v13.4.0, I encountered an issue where the default locale was not recognized. Despite following the documentation step by step, I also faced significant challenges with the client-side version in p ...

How can I store the data retrieved from an API and then forward it to a URL using Angular?

Is there a way to save and pass the data received from an API to a URL in Angular? SERVICE.ts readonly apiUrl = 'http://localhost:49940/'; constructor(private http: HttpClient) { } getUserName(): Observable<any> { return this.http.ge ...

Transmitting image data (blob) from the frontend to the backend using Next.js and tRPC (T3 stack)

I'm currently facing a challenge in sending a leaflet map image from the backend to the frontend using the leaflet-simple-map-screenshoter library for capturing the image. The library returns a blob, which I need to transmit back to the backend and sa ...