Typescript HashMap implementation with Lists as values

Currently delving into TypeScript, I am attempting to generate a collection in a manner akin to the following Java example:

HashMap<String, List<String>> hashMap = new HashMap<String,List<String>>();

Struggling to locate any relevant examples. Is it feasible to replicate this functionality in Typescript? Are there comparable alternatives available?

Answer №1

HashMap ensures that keys are unique. You can easily assign an array to a key using a simple object:

let hash = {};
hash["furry"] = [];
hash["furry"].push({ age: 4, name: "fluffy" });
console.log(hash)

Alternatively, you can utilize Record<Keys, Type>. According to the documentation:

Generates an object type with specified property keys as Keys and corresponding property values as Type. This feature allows mapping properties of one type to another.

interface DogInfo {
  age: number;
  name: string;
}
 
type DogBreed = "husky" | "poodle" | "corgi";
 
const dogs: Record<DogBreed, DogInfo[]> = {
  husky: [{ age: 5, name: "shadow" }],
  poodle: [{ age: 2, name: "bella" }],
  corgi: [{ age: 10, name: "rover" }],
};

UPDATE:

To add an item to Record<Keys, Type>, follow this approach:

dogs["husky"].push({ age: 8, name: "max" });

To retrieve items from Record<Keys, Type>, use this method:

const huskies: DogInfo[] = dogs["husky"];

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

How can CSS positioning be utilized to align lines accurately?

Recently, I created a basic jsbin to draw a line connecting two points. It doesn't rely on any drawing libraries; just plain JavaScript and jQuery. I managed to calculate the angle using code I found in this library. When dragging the circle at the ...

Is there a way to mimic this type of scrolling effect?

Upon visiting this website, it is evident that the entire interface has been constructed with React. The scrolling experience on this site is exceptionally smooth, although it may feel slightly more substantial than a typical scroll. After researching onli ...

Distinguish among various mat accordion types

I created a custom wrapper for the mat accordion component in Angular Material to handle multiple accordions with different behaviors based on user interaction. Here is my implementation: Wrapper Mat Accordion HTML <mat-accordion> <mat-expa ...

Update information in a table row and store it in the database using Ajax

Looking for some guidance with ajax and javascript here. I'm not very proficient in this area, so any help would be greatly appreciated. I have a table on my page where data is displayed like this: <table class="table table-bordered"> ...

The feature to toggle push notifications is missing in Xcode 11, and is also not available in the capability settings

I'm currently developing an Ionic project and trying to incorporate FCM Push notifications. I am unable to locate the toggle push notifications option in the signing & Capabilities tab in Xcode. ...

Could anyone clarify the workings of the async function in this specific useEffect situation?

Within a child component, there is an onClick event: onClick={()=>{ //2. an image is clicked, and the choice is added to the choiceOrder state, and then a jsonupdate is called -- 3. in ChooseBy.js //onclick, add or remove the choice choosebyprop ...

The absence of the google-services.json file has rendered the Google Services Plugin inoperable. Attempted search location:

Having an issue while trying to integrate my app with Firebase. The error message keeps indicating: > File google-services.json is missing. For a more detailed view of the error, please refer to the image below: https://i.stack.imgur.com/sgNYu.jpg D ...

Developing a custom React component library using Webpack and Typescript, however encountering issues with Webpack consistently bundling React

I'm currently in the process of developing an external component library using Webpack and TypeScript. Although it compiles without any issues, I encounter an error when attempting to use the library: Invalid hook call. Hooks can only be called ins ...

What is the error message "Cannot assign type 'IArguments' to argument"?

Currently employing a workaround that is unfortunately necessary. I have to suppress specific console errors that are essentially harmless. export const removeConsoleErrors = () => { const cloneConsoleError = console.error; const suppressedWarnings ...

What is the correct way to import the THREE.js library into your project?

I recently added the three library to my project via npm. Within the node_modules directory, there is a folder named three. However, when I tried to import it using: import * as THREE from 'three'; I encountered the following error: ReferenceEr ...

Issues with the plugin for resizing text to fit the parent div's scale

I've spent the last hour attempting to get this script to function properly, but no luck yet. Check out the correct jsfiddle example here: http://jsfiddle.net/zachleat/WzN6d/ My website where the malfunctioning code resides can be found here: I&apo ...

Tips on making an array readable by JavaScript using Jinja2 and Google App Engine

I'm currently facing an issue with transferring an array from a server to a web page through Jinja2 in Google App Engine. Despite my efforts, I'm struggling to make the array readable by my jQuery code. This is all new to me as it's my first ...

"Utilizing Vue.js for frontend, this app utilizes axios from the client side, rather than

As a newcomer to the world of programming, I apologize if my question sounds basic. I currently have a setup where a Vue.js application is running on a Linux Red Hat server with Apache installed via XAMPP. Additionally, an ASP.NET Core 6 Web API applicatio ...

When using a Kendo Grid with a Checkbox as a column, the focus automatically shifts to the first

Whenever I select a checkbox in my Kendo grid, the focus automatically shifts to the first cell of the first row. How can I prevent this from happening? Here is the code I am currently using when a checkbox is checked: $('#approvaltranslistview' ...

Top method for changing classes in Angular

Within my Angular4 application, I've implemented a method to conditionally apply two classes as seen below: <some-element [ngClass]="{ 'fa-toggle-on': category.active, 'fa-toggle-off': !category.active }"> </some-element& ...

Troubleshooting issue with the spread operator and setState in React, Typescript, and Material-ui

I recently developed a custom Snackbar component in React with Material-ui and Typescript. While working on it, I encountered some confusion regarding the usage of spread operators and await functions. (Example available here: https://codesandbox.io/s/gift ...

Understanding the significance of emitDecoratorMetadata in transpiled code

I have a question regarding the significance of the emitDecoratorMetadata option when transpiling TypeScript to JavaScript in an Angular 2 environment. If this option is set to false, and metadata is not included in the final code, what impact will it ha ...

When using Magento, pasting the same link into the browser produces a different outcome than clicking on window.location - specifically when trying to add items to the

I'm in the process of setting up a Magento category page that allows users to add configurable products directly from the category page, which is not the standard operation for Magento. After putting in a lot of effort, I have almost completed the ta ...

Is there a way to trigger the click event in the week view of an Angular 2+ calendar?

https://i.sstatic.net/Vx2x8.png HTML Templates <mwl-calendar-week-view [viewDate]="viewDate" [refresh]="refresh" (click)="weekDayClick($event)"> </mwl-calendar-week-view> In the component file weekDayCl ...

Create proper spacing for string formatting within an AngularJS modal

I am working with a popup that displays output as one string with spaces and newline characters. Each line is concatenated to the previous line, allowing for individual adjustments. Test1 : Success : 200 Test2 : Su ...