TypeScript does not have access to the array prototype

Despite searching through various stack overflow responses, I haven't been able to resolve my error. I've attempted the following:

A B

Below is my TypeScript code snippet:

interface Array<T> {
  asyncForEach(callback: CallableFunction): void;
}

Array.prototype.asyncForEach = async function (callback: CallableFunction) {
  // this represents our array
  for (let index = 0; index < this.length; index++) {
    // We call the callback for each entry
    await callback(this[index], index, this);
  }
};

(async () => {
  const buttons: string[] = [things.methButtonId, things.cashButtonId];

  buttons.asyncForEach(async (button) => {
    for (let i = 0; i < 1000; i++) {
      //do something
    }
  })
});

Upon building, I encountered the following errors:

src/index.ts:13:17 - error TS2339: Property 'asyncForEach' does not exist on type 'any[]'.

13 Array.prototype.asyncForEach = async function (callback: CallableFunction) {

src/index.ts:39:11 - error TS2339: Property 'asyncForEach' does not exist on type 'string[]'.

39 buttons.asyncForEach(async (button) => {

Additionally, Visual Studio Code displayed the following error message:

Property 'asyncForEach' does not exist on type 'any[]'.ts(2339)

Provided below is my configuration file:

{
  "compilerOptions": {
    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es2020",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    ... 
  }, "include": ["./src/*.ts", "src/index.js"]
}

I would greatly appreciate any assistance with resolving this issue.

Answer №1

@CherryDT's feedback is spot on!

Here is the code snippet I'm using:

declare global {
  interface Array<T> {
    asyncForEach(callback: CallableFunction);
  }
}

Array.prototype.asyncForEach = async function (callback: CallableFunction) {
  // iterating through each element of the array
  for (let index = 0; index < this.length; index++) {
    // executing the callback function for each element
    await callback(this[index], index, this);
  }
};

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

Having difficulty transitioning a function with a promise from JavaScript to TypeScript

I am currently in the process of transitioning my existing NodeJS JavaScript code to TypeScript for a NodeJS base, which will then be converted back to JavaScript when running on NodeJS. This approach helps me maintain clear types and utilize additional fe ...

NG01203: The form control with the name 'name' does not have a specified value accessor

This question was originally posted by JOYBOY but was later deleted. The title of the question was NG01203: No value accessor for form control name: 'name' In my Angular 18 application, I am utilizing both standalone components and module-based ...

List the attributes that have different values

One of the functions I currently have incorporates lodash to compare two objects and determine if they are identical. private checkForChanges(): boolean { if (_.isEqual(this.definitionDetails, this.originalDetails) === true) { return false; ...

Unable to set the opacity of rc-tooltip to 1

Despite customizing our tooltips with CSS, we are still experiencing an issue where the tooltips appear translucent rather than having an opacity of 1. This is evident in the image provided (with text visible in the background): https://i.sstatic.net/nlM ...

Updating the Nuxt3 editing page with useFetch and $fetch for fetching data, along with a typed storage object that prevents loading issues

My journey with nuxt3 is still new. I am currently working on developing a new API-based app with nuxt3. Previous versions seemed to work "somehow," but they did not meet my expectations. Here are the things I am looking to cover, both in theory and in cod ...

Calculating the average of duplicate values in a multidimensional PHP array

I'm in a bit of a pickle trying to add comprehensive product review data to SKU records, particularly getting the average value of duplicated keys. Array ( [0] => Array ( [sku] => 70835 [rating] => 5 ...

Acquiring nested elements from a list in R

Is there a way to extract embedded elements from a list using the lapply function in R? The original list contains arrays, and after using the gpagen function from the geomorph package, a new list is generated with embedded elements that need to be extract ...

Setting state in a functional component is not possible when data is being fetched from Firebase in a ReactJS application

useEffect(() => { console.log("mounted"); all.db.ref("NewDonor").on("child_added", (data) => { var DataFromDB = data.val(); state.donor.push(DataFromDB); console.log(state.donor); setState({ donor: DataFromDB ...

create an endless loop to animate in angular2

Is there a way to add iterations, or something similar to the ccs3 animation-iteration-count in Angular 2 animations? I've looked but can't find anything related. How can we apply an infinite play to the animation? Where should we include that o ...

What would be a colloquial method to retrieve the ultimate result from the iterator function?

I've got a rather complex function that describes an iterative process. It goes something like this (I have lots of code not relevant to the question): function* functionName( config: Config, poolSize: number ): Generator<[State, Step], boo ...

I am currently facing an issue related to the length property. It is showing an ERROR TypeError: Cannot read property 'length' of undefined

Is it recommended to set the length to be inherited from Angular right? If so, why am I getting this error: "MyPostsComponent.html: 7 ERROR TypeError: Cannot read the 'length' of undefined property" when fileList.length is greater than 0? onFile ...

Issues with maintaining the checked state of radio buttons in an Angular 4 application with Bootstrap 4

In my Angular 4 reactive form, I am struggling with the following code: <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary" *ngFor="let item of list;let i=index" > <input type="radio" name="som ...

Error message "Index out of range in Swift arrays"

Hello, I'm having trouble printing the elements of an array in reverse order as I keep getting an error that says: Array index out of Range. Could anyone offer some assistance? Below is the code I am using: import UIKit class DecimalToBinaryView ...

Issue with Angular2 - namespace webdriver not detected during npm installation

Upon restarting my Angular2 project, I ran the npm install command and encountered this error message: node_modules/protractor/built/browser.d.ts(258,37): error TS2503: Cannot find namespace 'webdriver' Does anyone have insight into the origin ...

How can I utilize Material-UI's DataGrid component to incorporate multiple layers of text within a single cell?

I'm having trouble displaying two separate lines of text in a single cell using Material-UI's datagrid component. Here is the code I have attempted: const columns: ColDef[] = [ { field: "name", headerNam ...

Transform the array into a series of chained methods

I'm facing a challenge with an array structure that looks like this... $data = [ 'columns' => [ [['increments', 'id']], [['string', 'key'], ['index']], [[&apos ...

unable to retrieve and transform the data into a structured format

In Python, I have some data that is stored as a string and looks like this: ('single image encodings************', '[-0.0810571 0.07765304 -0.01207364 -0.07887193 -0.10862262 0.00894677\n 0.02332557 -0.13491267 0.17760251...]&apos ...

The loading template remains visible despite the Eventsource being closed when using the Async Pipe

How can I resolve the issue I'm facing with the Angular async pipe and event source while using Spring boot WebFlux? I need to display a "loading data" message until the API call is complete. Once the API fetches data, I want to show the retrieved dat ...

Having trouble looping through an array in Angular 2?

I am currently using a FirebaseObjectObservable to retrieve the value of a property from my firebase database. The property can have multiple values, so I stored them in a local array variable. However, I ran into an issue while trying to iterate through ...

Tips for adjusting the radio button value similarly to a checkbox in Angular 2 using *ngFor

my checkbox and radio button implementation: <input id="{{k.group_name}}_{{i}}" name="{{k.group_name}}" type="checkbox" class="hide" name="{{k.group_name}}" [value]="m.details" (change)="change($event, m , k.item_ingredient_group_key,false,k.maximum)"& ...