Working with Typescript: creating closures within a loop

I've encountered a challenge while attempting to incorporate closures in Typescript within a loop. The issue I'm facing is quite significant.

for(let car of vehicles) {
    update(location => 
        {
            car.location = location;
        }
    );
}

When compiling using Typescript 1.8.1 and targeting ES5, the following error emerges:

Loop contains block-scoped variable 'car' referenced by a function in the loop. This is only supported in ECMAScript 6 or higher.

Using var instead of let in the loop results in all closures utilizing the last value of car. Are there any effective workarounds for this issue when targeting ES5?

Answer №2

The issue arises from the fact that the function being called in the update is linked to the variable 'vehicle', rather than the specific vehicle being iterated over in the loop. To address this, you could try something along these lines:

for(let car of cars) {
    (carClosure => {
        update(position => carClosure.position = position)
    })(car)
}

Alternatively, you could utilize a JavaScript runtime that supports scoping with let, which would likely yield the desired outcome.

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

Developing step code for CucumberJS Scenario Outlines

In my feature file, I have the following scenario outlined for testing colors: Feature: Color feature @test Scenario Outline: Test color Given the first color is <COLOR_ONE> And the second color is <COLOR_TWO> ...

The pagination feature in ag-grid is malfunctioning, causing it to initially send a request to

Upon clicking the search button, a server call will be made to retrieve results and display them in the ag grid. The server will only return the specified number of records based on the pagination details provided with each click. Despite implementing the ...

I'm having trouble getting my Node.js and TypeScript project to run because I keep encountering the error message ".ts is recognized as an unknown file extension."

I encountered the following error message: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" This issue arose after inserting "type": "module" into the package.json package.json { "name": &qu ...

typescript error in navigating with parameters

Having trouble adding a param with TypeScript and encountering the following error: Error: Argument of type '["Profile", { screen: Screen; }]' is not assignable to parameter of type '[screen: "Explore"] | [screen: "E ...

Delete a particular item from a JSON object in real-time using TypeScript/JavaScript

Upon examining the JSON data provided, it contains a node called careerLevels which includes inner child elements. input = { "careerLevelGroups": [ { "201801": 58, "201802": 74, ...

The specified file cannot be found within the Node file system

I am working on a project that involves reading a file using Node fs, and I have the following code: const files: FileSystemTree = { "Component.tsx": { file: { contents: fs.readFileSync( `../../apps/components ...

Using Typescript to specify the parameter type of a function as a generic function

After creating a function called compose, it looks like this: const composeTyped = <T, U, R>(f: (x: T) => U, g: (y: U) => R) => (x: T) => g(f(x)); It appears to me that both functions f and g fall under the type fGeneric, which is define ...

Tips for preventing the overwriting of a JSON object in a React application

I'm trying to compare two JSON objects and identify the differing values in the second JSON object based on a specific key. My goal is to store these mismatched values in a new JSON object. The current issue I'm facing is that when there are mult ...

Iterate through the complex array of nested objects and modify the values according to specified conditions

I am currently iterating through an array of objects and then delving into a deeply nested array of objects to search for a specific ID. Once the ID is found, I need to update the status to a particular value and return the entire updated array. Issue: Th ...

Using ng-template in ContentChildren causes the component to throw an ExpressionChangedAfterItHasBeenCheckedError

I've encountered the ExpressionChangedAfterItHasBeenCheckedError error while working on an Angular project, and this time I'm stuck on how to resolve it. The component I'm dealing with has child components utilizing @ContentChild and @Conte ...

Building a TypeScript JSON API without the need for the "any" data type

It seems like creating a generic JSON type interface in TypeScript may be challenging due to the return type of the native JSON.parse function being any. Despite this, I have been exploring ways to achieve this and found a solution on GitHub that is very c ...

Displaying a TypeScript-enabled antd tree component in a React application does not show any information

I attempted to convert the Tree example from antd to utilize TypeScript, however, the child-render function does not seem to return anything. The commented row renders when I remove the comment. The RenderTreeNodes function is executed for each element in ...

Extending Enums in Typescript: A Comprehensive Guide

How can you work with a list of constants or Enum? Here is an example: enum MyList { A, B } enum MyList2 { C } function process<T>(input:MyList | T):void { } process<MyList2>(123) // The compiler does not recognize that 123 ...

Reading a variable within the fileReader onload function in TypeScript

When attempting to upload an image by reading a base64 path using file reader, I initially encountered issues with variable updates outside of the FileReader onload function. Here is the original code snippet: const reader: FileReader = new FileReader(); ...

Incorporating Auth0 into NestJS for Enhanced Security on gRPC Endpoints

I have been working on implementing NestJS Guards for Authentication and Authorization in my gRPC Services built with NestJS. @GrpcMethod(USER_SERVICE_NAME, 'GetUser') private getUser(req: GetUserRequest): Promise<GetUserResponse> { ret ...

Running compiled TypeScript in the web browser will not execute properly

While my TypeScript code compiles correctly, I have encountered a problem with my class structure that results in unexpected behavior and runtime errors. The specific issue causing the error is this.Scene = new THREE.Scene(); After running tsc, the lin ...

Bring in TypeScript property from an external scope into the current scope

I am encountering an issue with my TypeScript code. Inside the anonymous functions, I am unable to change the properties of the class because they are out of scope. Is there a way to pass them in so that they can be modified? class PositionCtrl { ...

Error arises when attempting to pass interface props to a component in a React Typescript application

I am currently delving into the world of React js and typescript. As part of my learning process, I have created a demo application that allows users to input their name and age. The app features an ErrorModal that should pop up on the screen whenever inco ...

Enhancing AntDesign 3.x with the Latest Version of Momentjs

Broken upgrade guide on the AntD website. What is the best way to update AntDesign 3.x's moment dependency to the latest version of moment? The value prop of AntD's DatePicker's RangePicker relies on its own momentjs. Therefore, if you want ...

Setting up NextJs in Visual Studio Code with Yarn

When I used yarn create next-app --typescript to set up a TypeScript Next.js application with Yarn, everything seemed to be working fine with the command yarn run dev. However, Visual Studio Code was not recognizing any of the yarn packages that were added ...