List in TypeScript: The Power of Generics

I am currently delving into TypeScript and seeking guidance on implementing generic collection types. I have discussed dictionaries and HashSets in a previous question; here, I would appreciate any feedback specifically regarding my list type.

The ForEach-Operation seems a bit unconventional to me. I came across it in another question and tried to enhance it by returning true or false to indicate if the iteration was prematurely halted or completed.

import { IForEachFunction } from "./IForEachFunction"

export class List<T> {
    private _items: Array<T>;

    public constructor() {
        this._items = [];
    }

    public get Count(): number {
        return this._items.length;
    }

    public Item(index: number): T {
        return this._items[index];
    }

    public Add(value: T): void {
        this._items.push(value);
    }

    public RemoveAt(index: number): void {
        this._items.splice(index, 1);
    }

    public Remove(value: T): void {
        let index = this._items.indexOf(value);
        this.RemoveAt(index);
    }

    public ForEach(callback: IForEachFunction<T>): boolean {
        for (const element of this._items) {
            if (callback(element) === false) {
                return false;
            }
        }

        return true;
    }
}

The ForEach-Iteration relies on an interface defined in another file:

export interface IForEachFunction<T> {
    (callback: T): boolean | void;
}

To utilize my list and the ForEach method, follow this example:

let myList: List<a_type> = new List<a_type>();
let completed: boolean = myList.ForEach(xyz => {
    // perform actions with xyz
    return false; // interrupts the iteration
    return true; // continues to the next element
});
if (completed) // assesses what occurred "during" the iteration

In my opinion, this implementation is satisfactory, but I welcome any constructive criticism. I'm unsure about my usage of ===. Additionally, I'm curious about how to define a function that aligns with the IForEachFunction interface. Can I create a method adhering to the interface definition without employing an anonymous function as depicted above?

Thank you! Ralf

Answer №1

One issue that stands out is the presence of an interface instance:

callback: IForEachFunction<T>

Within this, there is a method named

callback()

However, callback is only invoked once. To properly utilize the interface, you should call the 'callback()' method within it:

callback.callback()

It appears that your code may be influenced by C# or Java. In TypeScript, it's common to simply use arrays for similar functionalities. This can streamline certain aspects of your code.

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

A step-by-step guide to setting up Firebase Cloud Messaging in Angular 2

Looking to set up Firebase Cloud Messaging in Angular2 / TypeScript / AngularFire2? You can find detailed instructions for configuring it with JavaScript at this link: https://firebase.google.com/docs/cloud-messaging/js/client ...

Error message "Unknown provider: $stateParams encountered when utilizing ui-router's resolve function in Typescript"

I am facing a challenge in converting an Angular ui-router configuration file with multiple states and resolves to Typescript. Everything seems to work fine until I introduce the $stateParams, which leads to the 'Unknown provider' error. I have t ...

Ways to retrieve class attributes in a child context

When trying to access the class properties (or methods) from another scope, I find myself having to store it in a local variable within the function scope. class MyClass { constructor(API) { this.API = API; this.property = 'value& ...

Tips for delaying code execution in Angular until the service constructor has been called and completed

I have successfully stored the api_url in IndexedDB using NgxIndexedDBService. However, I am encountering an issue where I need to fetch the api_url before any service call is made. The problem arises when I attempt to call a service method from the constr ...

Error message displayed indicating script not found after executing yarn tsc within a Docker container

Using docker, I successfully built my project by running yarn tsc. However, when I executed docker run -p88:5011 accounts2 I encountered the following error: PM2 error: Error: Script not found: /home/accounts/dist/server/index.js. This error occurs despit ...

Modify the parent component using dialogRef while keeping the dialog open

Within my application, there is a child dialog connected to a parent component. The parent component contains a MatTable that gets updated when the "update" button in the child dialog is clicked. The following code in the parent component is functioning p ...

Tips for utilizing JSON in a TypeScript file within a Node.js environment

I have been working on implementing JSON type in my Node.js application, but I am encountering some data in a scripted format. Here is the response: }, data: '\x1F\b\x00\x00\x00\x00\x00\x00\x00]PMo0\f ...

What is the best way to modify the NgbDatePicker format in Angular 4 from YYYY-MM-DD to MM-DD-YYYY?

Hello, I am currently using ngbDatePicker with a format of YYYY-MM-DD and I have been trying to change it to MM/DD/YYYY without success. Here is the HTML code: <div class="form-group datepicker"> <label for="dob">Date of Birth*</ ...

Can we modify the auto-import format from `~/directory/file` to `@/directory/file`?

I have a small issue that's been bugging me. I'm working on a project using Nuxt3 and Vscode. When something is auto-imported, Vscode uses the ~/directory/file prefix instead of the preferred @/directory/file. Is there an easy way to configure Vs ...

Is it possible to denote two "any" as the same thing in a TypeScript function signature?

Here is a function to extract items from an array based on a checker function: function extractItemsFromArray(array: any[], isItemToBeRemoved: (item: any) => boolean) { let removedItems = []; let i = array.length; while(i--) if(isItemToBeRemo ...

What is the best method for accessing Blob data in Deno?

Currently, I am attempting to read from a websocket within Deno. Below is the code snippet (please note that you will require an API key from AISstream for it to function properly) /** * URL used by the API; this might change if the version changes or at ...

The assigned type does not match the mapped type

When looking at the following example, the error Type 'string' is not assignable to type 'MapType<ReturnT>'.(2322) confuses me. The return type of the strToTs function is actually string | number | any, depending on a different ty ...

Tips for resolving the TypeScript error related to the global object in Node.js

I am currently working on a project following the steps outlined in this guide https://vercel.com/guides/nextjs-prisma-postgres to develop a full stack application. However, I have encountered an error with TypeScript in the code snippet below: import { Pr ...

What steps can I take to stop Vetur and TypeScript from displaying duplicate TypeScript warnings in VSCode?

I have a Vue2 project using TypeScript in VSCode with Vetur and TypeScript extensions installed. Whenever there is a TypeScript warning, both the TypeScript and Vetur overlays show duplicate warnings. Example of duplicate warnings Also, the intellisense ...

Strategies for preventing multi-level inheritance of TypeScript class properties and methods

In my current JavaScript class structure, the DataService is defined as follows: // data.service.ts export class DataService { public url = environment.url; constructor( private uri: string, private httpClient: HttpClient, ) { } ...

In the event that you encounter various version formats during your work

Suppose I have a number in the format Example "1.0.0.0". If I want to increase it to the next version, it would be "1.0.0.1" By using the following regex code snippet, we can achieve this perfect result of incrementing the version to "1.0.0.1": let ver ...

What is the best approach for determining which CSS file to import in next.js?

I'm currently facing the task of selecting which CSS file to apply in my next.js project. I have two separate CSS files, one for desktop and one for mobile devices. My current method of importing CSS files is as follows: // _app.tsx import ".. ...

Differentiating between model types and parameters in Prisma can greatly enhance your understanding of

Consider the following scenario: const modifyData = async(data, settings) => { await data.update(settings) } In this case, the data refers to any data source, and the settings consist of objects like where and options for updating the data. How can ...

Steps for disabling the websocket when the component is unmounted

Below is a snippet of my code. I am attempting to close the websocket connection when the component unmounts, but I'm unsure of the proper approach. Within the same component, I am using useEffect along with useRef to ensure that only one instance of ...

Exploring i18nNext integration with antd table in React

Presently, this is the UI https://i.stack.imgur.com/CMvle.png App.tsx import "./styles.css"; import MyTable from "./MyTable"; export default function App() { const data = [ { key: "1", date: "2022-01- ...