Tips for looping through a Set in TypeScript

What is the best way to loop through a set in TypeScript? Using for..of does not seem to work properly:

'Set<string>' is neither an array nor a string type

Using .forEach is not ideal since it obscures the context of this. I would rather avoid using a while loop with a try catch block. Is there something I am overlooking? Surely, it shouldn't be so complicated that it requires a try {while} catch {} approach.

Answer №1

@SnareChops was spot on:

mySet.forEach(function(item){
    // handle "this"
}, **this**);

This method is effective.

I suppose:

for(item of mySet.values()){
}

Would be successful if I didn't have to deal with es-shim complications causing issues. However, the use of the shim stuff is recommended by the Angular 2 developers so ¯\_(ツ)_/¯

The only other solution that functioned was:

for (var item of Array.from(set.values())) {
}

or something along those lines, which is less than ideal.

Answer №2

Building upon the top-rated response, it is also ensured to be type-safe when utilizing let for the iteration variable, like so:

for (let item of groupOfItems) {
   ... perform actions with item...
}

By following this approach, it guarantees that item will possess the specific type Y, provided that groupOfItems was initialized as Set<Y>.

Answer №3

Employing a standard function instead of an arrow function allows you to still utilize .forEach with the appropriate this

mySet.forEach(function(item){
    expect(this).toEqual(item);
});

In comparison:

class MyClass{
    ...
    doSomething():{
        mySet.forEach((item) => {
            expect(this instanceof MyClass).toEqual(true);
        });
    }
}

Alternatively, you can iterate using a for loop over the values

for(item of mySet.values()){
    ...
}

For additional information on iterating through a Set using foreach, click here

Answer №4

To utilize the `for ... of` statement in TypeScript, include `"es6"` as a `"lib"` in your compiler options and set `"es6"` as the target. Alternatively, you can use `"es2015.iterable"` instead of `"es6"` in your lib if it better meets your requirements.

Here is an example configuration for your tsconfig.json file:

{
    "compilerOptions": {
        "target": "es6",
        "lib": [
            "es6",
            "dom"
        ]
    },
    "exclude": [
        "node_modules"
    ]
}

For more information on this topic, refer to the related issue on GitHub: https://github.com/Microsoft/TypeScript/issues/12707

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

NativeScript Error Code NG8001: Element 'ActionBar' is unrecognized

In my project, the startupscreen module setup is as follows: import { NativeScriptFormsModule } from "@nativescript/angular"; import { NativeScriptCommonModule } from "@nativescript/angular/common"; import { NgModule, NO_ERRORS_SCHEMA } ...

What is the process of declaring a variable within a class in TypeScript?

When setting up an instance variable inside my Angular component like this: @Component({ selector: 'app-root', templateUrl: './app.component.html', //template: `` styleUrls: ['./app.component.css'] }) export class AppCo ...

Angular Typescript Filter failing to connect with service injection

I am having trouble accessing the Constant app within a filter in Angular TypeScript. How can I successfully access a service inside a filter? Module App.Filter { import Shared = Core.Shared; export class MilestoneStatusFilter123 { static $inject = ...

Can Angular reactive forms be used to validate based on external conditions?

Currently, I am exploring Angular reactive forms validation and facing an issue with implementing Google autocomplete in an input field: <input autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="input-auto input" formControlName ...

Feeling lost about arrow functions in JavaScript

Here is the code I am currently using to increment the value of intVariable using window.setInterval. var Arrow = (function () { function Arrow() { this.intVariable = 1; this.itemId = -1; this.interval = 25; } Arrow.p ...

"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 ...

Barreling is essential for TypeScript custom paths to function properly

This morning has been dedicated to exploring ts-paths in order to shorten my import paths. After some experimentation, I have found that custom paths do work IF you set up barreling (having an index file that exports your modules) root ├── client ...

What's the process for deducing the default generic parameter from a function type?

Is there a way to extract the default type parameter of a function in order to make this statement compile successfully? const fails: string = "" as ReturnType<<T = string>() => T>; ...

Best Practices for Integrating Angular with Your Custom JavaScript Library

Imagine needing to create a TypeScript function that can be utilized across various components, services, or modules. For example, let's say you want an alert wrapper like this: my_alert(msg); // function my_alert(msg) { alert(msg); } You might hav ...

Optimal method for consecutively making N number of API calls in Angular 9 in a synchronous manner

Having a service method for API calls structured as follows: getUsers(id){ return this.http.get(`${env.apiURL}/id`) } Now, the requirement is to call this method for a list of users stored in an array: userId=[1,2,3,4,5,6,7,8,9] The goal is to retrieve ...

Creating an empty TypeScript variable with type FileList can be achieved by declaring the variable and initializing it with

After completing a coding test that required building a react app for uploading files using Typescript, I encountered a dilemma. Specifically, I needed to use the useState hook to store the uploaded file and set its default value. Typically, setting the de ...

TypeScript Add Extract Kind

I am currently working on implementing a function called sumPluck. This function will allow the user to specify a property of type number from an object in an array, and then calculate the sum of all those properties. For example: type A = { prop: number ...

Can anyone suggest a more efficient method for validating checkbox selection in Angular?

I am working with an angular material stepper, where I need to validate user selections at each step before allowing them to proceed. The first step displays a list of 'deliveries' for the user to choose from, and I want to ensure that at least o ...

"Trouble with Typescript's 'keyof' not recognizing 'any' as a constraint

These are the current definitions I have on hand: interface Action<T extends string, P> { type: T; payload: P; } type ActionDefinitions = { setNumber: number; setString: string; } type ActionCreator<A extends keyof ActionDefinitions> ...

Type definition for Vuex store functionality

Working on creating a versatile type to provide typing hints for mutations in Vuex. After reading an inspiring article on Vuex + TypeScript, I decided to develop something more generic. Here is what I came up with: export type MutationType<S, P, K exten ...

Issue with Angular 2: Service not reflecting updated variable

I am currently working on creating an API service and trying to assign the data to a variable. However, I am facing an issue where the variable is not updating and ends up being undefined when I try to log it after calling the API service. import {Compone ...

Tips on obtaining checkbox values other than "true"

Having trouble retrieving the values of selected checkboxes instead of displaying "Custom Category"? I've attempted to access the values and attributes with no success. I'm aiming to display the values of the selected checkbox. app.component.ht ...

Tips for utilizing jest.mock following the removal of @types/jest (^jest@24)

After upgrading from version 7 to version 8 of @angular-builders/jest, I followed the instructions provided in the migration guide which advised removing @types/jest since it now comes bundled with Jest v24. Additionally, changes were made to my tsconfig a ...

Tips for sending a file rather than a json object in nextjs

Is there a way to send a file from either route.ts or page.ts, regardless of its location in the file-system? Currently, I am using the following code in my back-end python + flask... @app.route("/thumbnail/<string:filename>") def get_file ...

Transforming two child arrays within an object into a single array using Ramda

I am looking to transform an object into an array. The object I have is structured like this: const data = { t1: [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ], t2: [ {" ...