What is causing certain code to be unable to iterate over values in a map in TypeScript?

Exploring various TypeScript idioms showcased in the responses to this Stack Overflow post (Iterating over Typescript Map) on Codepen.

Below is my code snippet.

class KeyType {
  style: number;
  constructor(style) {
    this.style = style;  
  };
}

function test() {


  const someMap = new Map<KeyType, number>();
  someMap.set(new KeyType(style=199), 5);
  someMap.set(new KeyType(style=67), 90);

 console.log('testing 1')

  for (let [k, m] of someMap) {
    console.log(`1 k ${k} m ${m}`);
  }

   console.log('testing 2')

  for (let [k, m] of someMap.entries()) {
    console.log(`2 k ${k} m ${m}`);
  }

   console.log('testing Object entries')

  for (let [k, m] of Object.entries(someMap)) {
    console.log(`3 k ${k} m ${m}`);
  }

  console.log('forEach method')

  someMap.forEach((v, id) => console.log(`3 v ${v} id ${id}`))

  Array.from(someMap.entries()).forEach(entry =>
    console.log(`4 k ${entry[0].style} m ${entry[1]}`)
  )

  const ar = Array.from(someMap.keys());
  console.log(ar[0].style);

}

My confusion arises from the fact that all the forEach method functions as expected, while the for (let [k,m] of someMap) {... does not seem to work at all.

Could it possibly be an issue with CodePen's TypeScript setup? Or have I made an error within the testing 1, testing 2, and testing Object entries sections above?

I intended to try installing ts-node for local testing but encountered different problems during its installation process.

Answer №1

Start by addressing the errors present in your code.

someMap.set(new KeyType(style=199), 5);

This snippet is incorrect JavaScript/TypeScript syntax. If you intend to pass `199` as an argument, modify it like so:

someMap.set(new KeyType(199), 5);

The next issue involves how the `KeyType` class is serialized for console output.

  for (let [k, m] of someMap) {
    console.log(`1 k ${k} m ${m}`);
  }

In this block, `k` represents `KeyType`, which in your context refers to a class. By default, JavaScript serializes classes as "[object] Object", which may not be desired.

If your goal is to log the `style` attribute of `KeyType`, replace the code with this:

  for (let [k, m] of someMap) {
    console.log(`1 k ${k.style} m ${m}`);
  }

You can view the final corrected version on TypeScript Playground.


Note: Beware of variable overshadowing. While your class is named `KeyType`, there is also a global type with the same identifier.

type KeyType = "public" | "private" | "secret";

In cases where your code exists without import/export statements, it will be treated as a script rather than a module. This means the global type takes precedence. Attempting to invoke `new KeyType()` will result in a compile-time error:

'KeyType' only refers to a type, but is being used as a value here.

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

Encountering an error while attempting to set up WebDriverIO with Typescript and Cucumber installation

After completing the project setup, the wdio.conf.ts and tsconfig.json files are saved in a folder named tests. However, the wdio.conf.ts file throws an error on this line: import type { Options } from "@wdio/types"; //located in wdio.conf.t ...

Invoking a function within an Angular component

I am facing a problem - is there a way to invoke a function from the name.component.html file without using a button click, and without needing to go through the .ts file or service? ...

How can I conceal the word "null" within an Angular 2 input field?

Whenever there is a null value in the JSON, it ends up displaying in the input field. How do I go about hiding it so that only the name shows up instead? <div> <input type="hidden" name="roleUserHidden-{{roleIndex}}" #role ...

What is the best approach to incorporate a refresh feature for a data stream?

I need to implement a function that updates the current list of items$ and allows for awaiting refreshItems(). This is my working implementation: private readStream = new Subject<T[]>(); readStream$ = this.readStream.asObservable(); getItems = (): ...

Guide to implementing scheduled tasks in a Node.js API using Express

Currently, my Node API has multiple endpoints, and while they work well for the most part, there is one endpoint that struggles with processing large requests taking up to 1 hour. To handle this, I am considering implementing a system where instead of wait ...

Declaring an array that holds Angular components in Angular 11: What's the best approach?

I'm trying to implement a feature in my Angular component where I can create a list that displays content from other components. My current approach involves declaring an array that contains references to different Angular components: import { Compone ...

Tips for transferring state information from a client to a server component within Nextjs?

Currently, I am working on a project where I need to read and write data from a locally stored .xml file that contains multiple <user> tags. The technology stack includes TypeScript and NextJS. The project is divided into three main components sprea ...

Cropping and resizing images

Within my angular application, I have successfully implemented image upload and preview functionality using the following code: HTML: <input type='file' (change)="readUrl($event)"> <img [src]="url"> TS: readUrl(event:any) { if ...

Error: Angular 6 resolve consistently returns undefined

Seeking to implement my service for retrieving values from the database server and displaying them onscreen, I have set up a resolver for the service since the database can be slow at times. However, no matter what I try, the data received through this.ro ...

Utilizing TypeScript Generics for Creating Arrays of Objects with Inherited Type Definitions

I'm exploring the concept of type inheritance for an array of objects, where one object's value types should inherit from another. While I'm unsure if this is achievable, it's definitely worth a try. Currently, I believe my best approac ...

The 'target' property is not found on the specified 'string' type

I've encountered an issue while creating a search bar in Typescript. Despite my efforts, the input is not being recognized. It seems that whenever I use the term 'target' in my onChange method, it triggers an error stating: Property &ap ...

search for a specific value within a nested subfield of an asterisk star field in Firestore

Here is the data I have: { root: { _rEG: { fen: 'value' }, _AS: { fen: 'value' }, _BSSA: { fen: 'value' } } } I would like to query using where('root.*.fen', '==', 'value'). ...

issue with mongoose virtual populate (unable to retrieve populated field)

During my project using mongoose with typescript, I encountered an issue with adding a virtual called subdomains to populate data from another collection. Although it worked without any errors, I found that I couldn't directly print the populated data ...

Exploring Parquet Files with Node.js

Looking for a solution to read parquet files using NodeJS. Anyone have any suggestions? I attempted to use node-parquet but found it difficult to install and it struggled with reading numerical data types. I also explored parquetjs, however, it can only ...

Changing the color of an Angular <div> element with scripting

I am currently working on an Angular 6 project and I need to change the colors of a div tag from a script after a click function. However, I also need to change it back to transparent. When I click on the "Inheritance" option, the background color of the ...

Looking to adjust the height of a foreignObject element within an SVG?

Looking to dynamically change the height of a foreignObject within an SVG, while also needing HTML elements inside it (working with ngx-graph). <foreignObject x="1" y="1" width="335" [height]="foreignObjHeight(node.Dat ...

Utilize React to display a Selected button within a whitespace

Currently, I am encountering an issue in React where I have a group of buttons at the bottom. Upon selecting a button, the corresponding text should display at the top within a specified whitespace. However, I am looking to have the whitespace already occu ...

Angular error: Attempting to reduce an empty array without an initial value

I am encountering an issue with my array being filtered and reduced. getPageComponents(title: string) { this.pageComponents = []; const pageBlock = this.pageComponents.filter((val) => { if (val.page_title === title) { retur ...

Set up Admin SDK using appropriate credentials for the given environment

As someone new to Node.js, Firebase Cloud Functions, and TypeScript, my objective is to create a cloud function that acts as an HTTP endpoint for clients to authenticate with Firebase. The desired outcome is for the cloud function to provide a custom acces ...

Guide to implementing ES2022 modules within an extension

After making changes in my extension code to test various module types, I decided to modify my tsconfig.json file as follows: { "compilerOptions": { "declaration": true, "module": "ES2022", ...