What is the proper way to define a Map in TypeScript?

In my TypeScript project, I'm trying to define a simple map structure with string keys and an object as a value. After researching on StackOverflow, this is the code snippet I've put together:

class Person {
    id: number;
    name: string;
}

interface PersonMap {
    [id: string]: Person;
}

Unfortunately, when attempting to use this declaration, TypeScript seems to interpret PersonMap as an array instead of a map. This means I am unable to access keys or values from the map:

let personMap = {} as PersonMap;

personMap[1] = {
    id: 1,
    name: 'John',
}

let people = personMap.values();

The error message I receive from TypeScript pertains to the last line above:

Property 'values' does not exist on type 'PersonMap'

I'm curious about the best approach for creating a Map in TypeScript, especially since it appears that TypeScript doesn't have a built-in ES6 Map type. Regardless, I prefer to come up with my custom Map implementation.

Answer №1

Have you considered using the Map data structure in JavaScript?

let employeesMap = new Map()

employeesMap.set("001", employee1)
employeesMap.set("002", employee2)

employeesMap.get("001")   =>  employee1

Another way to declare a map:

export const EmployeeMap = new Map([
  ["001", employee1],
  ["002", employee2]
])

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

Just updated angular-devkit and encountered an error message: Microsoft.AspNetCore.SpaServices[0]

After updating my Angular 8 and .NET Core 2.2 project from version 8.2.1 to 8.2.7, I noticed some messages in the console: fail: Microsoft.AspNetCore.SpaServices[0] <s> [webpack.Progress] 10% building 1/1 modules 0 active ..................... ...

Traverse a nested array containing children elements to construct a pathway map

I am currently working with a multidimensional array that contains children (subcategories): As I am setting up Angular routing, I receive this data format from an API. const items = [{ displayName: 'News', urlName: 'news', subca ...

Incorporate a typescript library into your Angular application

Recently, I added a text editor called Jodit to my angular application and faced some challenges in integrating it smoothly. The steps I followed were: npm install --save jodit Inserted "node_modules/jodit/build/jodit.min.js" in angular.json's bui ...

Adding an external component to an Angular 2 project

I've been facing challenges while trying to import an external component from a URL into a new Angular2 application. The issue I keep encountering is with the typescript failing to compile and run the application smoothly. Here is the specific import ...

Substitute terms in a sentence according to the guidelines

Looking to transform strings based on specific rules? "Hello {{firstName}}, this is {{senderName}}." Consider the following rules: rules = { firstName: "Alex", senderName: "Tracy" } The expected output would be: "Hello Alex, this is Tracy." If yo ...

Indexes in Typescript objects are used to access specific values

While Typescript has been mostly smooth sailing for me, I keep encountering a roadblock. Let's say I have a type that can be one of several strings: type ResourceConstant = 'A' | 'B' | 'C'; Now I want to create an objec ...

Issue: Unhandled promise rejection: BraintreeError: The 'authorization' parameter is mandatory for creating a client

I'm currently working on integrating Braintree using Angular with asp.net core. However, I've encountered an issue that I can't seem to solve. I'm following this article. The version of Angular I'm using is 14, and I have replicate ...

I received an eslint error message instructing me to "Delete the `CD`"

Just started learning Nestjs and I hit a roadblock when attempting to create my first .ts file. I encountered an error message that I'm struggling to comprehend. https://i.sstatic.net/pzhyn.png https://i.sstatic.net/VDH9o.png ...

Is there a way to showcase just the month in one spot when presenting data using Angular 13?

Just starting out with Angular and facing a challenge in the Milestone section. There is a loop for displaying years and months, but I need to ensure that the month name is displayed only once for each specific year. Can someone provide me with a possible ...

Tips for avoiding the use of import statements in Typescript

log.ts contains the code below import {LOG} from './log' LOG.e("tag","error"); LOG.f("tag","error"); LOG.d("tag","error"); I am looking for IntelliSense support in my TS file without affecting the output javascript. I only want this in my Java ...

Simple and quickest method for incorporating jQuery into Angular 2/4

Effective ways to combine jQuery and Angular? Simple steps for integrating jQuery in Angular2 TypeScript apps? Not sure if this approach is secure, but it can definitely be beneficial. Quite intriguing. ...

Why is TypeScript unable to recognize package exports? (using CommonJS as the module system and Node as the module resolution)

I have an NPM package that is built for ESM and CJS formats. The package has a dist folder in the root directory, which contains: dist/esm - modules with ESM dist/cjs - modules with CJS dist/types - typings for all modules In the package.json file, there ...

Promise rejection not caught: ; Zone: angular ; Task:

While using meteor and trying to set up a (click) attribute, I encountered the following error message. https://i.sstatic.net/Qzk9T.png This is my code: import { Component, NgZone, AfterContentInit } from 'angular2/core'; import { NgIf, NgFor ...

Why is Vite's hot reloading feature displaying unpredictable outcomes?

I have a unique setup consisting of Vite, Typescript, and Vue 3 SPA utilizing "script setup". This app is equipped with Urql to query data from a GraphQL endpoint. An interesting occurrence happens where the query results are only displayed after the comp ...

Display items in a visual format when they're contained within a JSON or object with NativeScript

Here is a snippet of JSON data: { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "pharmacy_id": "011E752345553380ABC13FFA163ECD15", "pharmacy_name": "Pharmacy", "lastUpdated": "2019 ...

Is there a way to implement retry functionality with a delay in RxJs without resorting to the outdated retryWhen method?

I'd like to implement a retry mechanism for an observable chain with a delay of 2 seconds. While researching, I found some solutions using retryWhen. However, it appears that retryWhen is deprecated and I prefer not to use it. The retry with delay s ...

Interpret information in Angular 2 using Typescript

Just starting with Angular (IONIC) and need help. How can I extract the userId or id from this code? his.response = data. //Looking for guidance on accessing Json keys Response : { "userId": 1, "id": 1, "title": "sunt aut facere repellat providen ...

Unable to access member function of Typescript class

I recently started using typescript and encountered an issue while working on a problem. I initially created the following class: export class ModuleInfoContainer extends Array<ModuleInfo> { constructor() { super(); } search(id: number) { ...

Next.js Enhanced with Google Analytics

I've been experimenting with integrating Google Analytics into Next.js, following a tutorial on YouTube - https://www.youtube.com/watch?v=lMSBNBDjaH8 Following the instructions in the video, I added these two scripts in _document.js: <script async ...

Next.js React Hydration Issue - "Anticipated a corresponding <a> within the server HTML <a>"

Currently, I am encountering a hydration error while working on my Next.js project. The specific error message that keeps popping up is: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected serv ...