Trying to retrieve a value from a map in TypeScript and getting the error "map.get is not a function"

I am currently facing an issue with my map implementation where I have strings set as keys and values. However, when attempting to retrieve a value using a key, I encounter an error.

Below is the code snippet that I am working with:

let map:Map<string, string> =  {  [ "key1": "hello world 1" ], ["key2": "hello world 2"] } ;
alert( JSON.stringify(map.get("key"))  );

The exception that was thrown is displayed below:

VM133:4 Uncaught TypeError: map.get is not a function
    at eval (eval at exec (typescript.js:41), <anonymous>:4:26)
    at exec (typescript.js:41)
    at HTMLDocument.runScripts (typescript.js:41)

If you could provide insights into what mistake I may be making, I would greatly appreciate it.

Thank you for your assistance.

Answer №1

In programming, a Map is considered a complex data structure and must be initialized with the constructor method (I believe Typescript should provide a warning for this).

To learn more about using Map, refer to the MDN documentation on Map.

If you are trying to use it, here's an example of how to create a Map:

const map:Map<string, string> = new Map([
  [ "key1", "hello world 1" ], 
  [ "key2", "hello world 2" ],
])

Answer №2

Consider implementing a typescript map with the correct constructor call as shown below. The current code is utilizing an object literal that is not properly formatted.

let myMap = new Map([
        ["key1", "value1"],
        ["key2", "value2"]
    ]);
alert( JSON.stringify(map.get("key1"))  );

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

Jest mock module request causing a timeout issue

I am encountering an issue with the code snippet below in my application request.ts import request from 'request' export const funcA = async ( apiToken: string, body: any): Promise<any> => { return new Promise((resolve, reject) =&g ...

The Add/Remove button functionality is not functioning as expected for duplicated form fields when using jQuery

I am experiencing an issue with the functionality of the "Add another" and "Remove row" buttons in my form. I implemented code from a specific Stack Overflow answer (jquery clone form fields and increment id) to create a cloneable section, but only the ori ...

Tips for setting variable values in Angular 7

I'm encountering an issue with assigning values to variables in my code. Can anyone provide assistance in finding a solution? Here is the snippet of my code: app.component.ts: public power:any; public ice:any; public cake:any; changeValue(prop, ...

A step-by-step guide to alphabetically sorting items in an auto-complete drop-down menu using AngularJS

<div class="custom-dropdown" name="pSelect" id="pSelect" ng-model="selectedP" ng-trim="false" ng-options="p as p.name for p in data"></div> This unique dropdown menu was created using AngularJS with data sourced from a JSON object. ...

A recursive approach for constructing a tree structure in Angular

Currently, I am working on a project involving the implementation of crud functions. To display the data in a tree-like structure, I am utilizing the org chart component from the PrimeNg library. The data obtained from the backend is in the form of an arra ...

Requesting data from a server using JavaScript/Ajax/Flash technologies over

Here is the code snippet I am currently using: swfobject.embedSWF("/Content/open-flash-chart.swf", "my_chart", "750", "300", "9.0.0", "expressInstall.swf", ...

AngularJS interprets expressions in the 'action' attribute

This afternoon I encountered a rather peculiar behavior with AngularJS. If "//" is present in an expression within the "action" attribute of a form, Angular will throw an interpolate error. Take a look at the code snippet below. When you run this code, t ...

Is there a way to simulate the Bun global object using Jest?

Currently, my tech stack includes Bun, Typescript (TS), and Jest. As I work on writing my tests, I encounter the need to mock Bun.file functionality. Here is a snippet from my tsconfig.json: { "compilerOptions": { "lib": ["ESNext"], " ...

Require data prior to initializing the angular constructor without using a resolver

Currently, I have a dialog service in place. In order to create the dialog component, I utilize viewContainerRef along with ComponentFactory. Once the component is created, I proceed to set a default value for a specific property within this component. t ...

Using Jquery to attach an event to a particular div which is part of a group of divs sharing

I am trying to implement a mouseup event on a series of divs that, when clicked, will reveal a child div ('menu'). All the parent divs have the same class. Here is an example: <div class="container"> <div class="menu"><p>Text ...

The utilization of paths in tsconfig.json does not successfully resolve when working with Angular

I'm trying to set up Angular to understand paths in order to avoid using relative paths when importing files. However, despite my efforts, it doesn't seem to be working. Here is my code snippet: //tsconfig.app.json "compilerOptions":{ //lot ...

Having trouble submitting ajax form data through nodemailer

Hey there, Recently, I created a web app using node.js and express. Everything seems to be working fine except for one issue - I am struggling to get the JSON data sent by AJAX into Nodemailer. Despite confirming that my AJAX is successfully sending the ...

Tips on transferring information from Node.js to JavaScript

I'm facing an issue while trying to retrieve data from Node.js in my JavaScript code as part of a specific task. Here is the Node.js configuration: app.get('',(req,res)=>{ res.render('index.ejs') }) app.get('/calculate ...

What are some ways to maintain consistent audio levels on a jquery volume slider?

My html5 webpage features a slider and an audio track, but I am not using the sound tag property controls="controls". I want the slider to control the volume of the audio file. When I include the following code in the body tags, everything works perfectly: ...

The utilization of "startIcon" and "endIcon" from the <Button/> API of Material-UI is restricted

I've been trying to work with this React code for a single component, but no matter what I do, I keep getting the same warning. I even tried copying and pasting the example, but the warning persists and the icon is not showing up. Can someone please a ...

Utilizing Typescript Generics in Arrow Function to Combine Two Arguments

For instance, I am working with this code in a .tsx file extension const Add = <T,>(arg0: T, arg1: T): T => arg0 + arg1; const A = Add(1, 2); const B = Add('1', '2') However, I am encountering an issue, as there is an error m ...

When an item in the accordion is clicked, the modal's left side scroll bar automatically scrolls to the top. Is there a solution to prevent this behavior and

When I first load the page and click on the Sales accordion, then proceed to click on Total reported and forecasted sales, the scrollbar jumps back up to the top The marked ng-container is specifically for the UI of Total reported and forecasted sales He ...

Selecting a particular item in a list depending on time using JavaScript, jQuery, or Angular

When working with a JSON file and binding it to list items, I have included a name/value pair in the json for each line indicating audio time, such as "time like 0, 5, 10 in seconds form". In my Cordova application, I am using a media plugin and implement ...

Using Angular JS to Implement Multi-filtering for Lists

Having trouble with the filter function in Angular JS when trying to filter a list using different links. I've been struggling to get it right even after trying some examples. Can anyone provide guidance on how to correctly filter the list? HTML < ...

Discover the steps to convert an image to base64 while circumventing the restrictions of the same-origin policy

I've been struggling to convert an image link to base64 in order to store it on the client-side browser (IndexedDB). Despite searching for a solution for days, I have not been able to find one that addresses my issue. While I can successfully convert ...