The map.get method in Typescript can sometimes return undefined when the key belongs to an interface type

I am facing an issue with my main.ts file where I have a map structure with keys defined by the interface dr and values stored as strings. However, when attempting to retrieve a value from the map using the get method, it returns undefined. Below is the snippet of my code:

interface dr {
a: string;
b: string;
}

let myMap = new Map<dr,string>();
myMap.set({ a: 'foo', b: 'bar' }, `this is my map`);

export default (a:string,b:string): string => {
return myMap.get({ a: a, b: b })!;

};

Answer №1

Object equality is unique when compared to primitive values, as objects are evaluated based on their references rather than property values.

let myMap = new Map<dr,string>();
myMap.set({ a: 'foo', b: 'bar' }, `this is my map`); 

In this case, setting { a: 'foo', b: 'bar' } in the map without storing the reference prevents you from retrieving it using get function.

To properly retrieve the object, you need to store and use the same reference:

var a = { a: 'foo', b: 'bar' };
myMap.set(a, `this is my map`);
myMap.get(a) // returns 'this is my map' 

Another approach is to convert the object into a string and use it as a key in the map:

var a = { a: 'foo', b: 'bar' };
myMap.set(`${a.a}${a.b}`, `this is my map`);
myMap.get('foobar') // returns 'this is my map'

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

Tips on adding JSX to Storybook controls

While using Storybook, I want to navigate to my component and test the behavior of the Docs tab by changing control values for each property. I have implemented a component called Footer that can accept types such as string | JSX.Element | React.FunctionCo ...

The Angular 2 view will remain unchanged until the user interacts with a different input box

I am currently working on implementing form validation using Reactive Forms in Angular 2. Here is the scenario: There are two input fields Here are image examples for step 1 and step 2: https://i.stack.imgur.com/nZlkk.png https://i.stack.imgur.com/jNIFj ...

What causes Gun.js to generate duplicate messages within a ReactJs environment?

I need assistance with my React application where gun.js is implemented. The issue I am facing is that messages are being duplicated on every render and update. Can someone please review my code and help me figure out what's wrong? Here is the code s ...

The potential cause of the hanging Angular page might be attributed to excessive memory consumption

Currently, I am working on a project that involves Angular, MySQL, Express, and Node-JS with Typescript. One of the key features of my project is an Angular Component that loads student data into a PrimeNG table from an API endpoint in my Node.js server. ...

Typescript: The type 'Observable<{}>' cannot be assigned to the type 'Observable'

I'm encountering an issue with the Observable type, any thoughts on how to resolve it? import { PostModel } from '../model/postModel'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable&ap ...

Incorporating external plugins with jQuery in Angular 2

My experience with Angular 2 and jQuery has been quite positive. I am eager to incorporate external libraries such as masonry-layout, but I have encountered a frustrating issue: When trying to use jQuery(...).masonry(), I receive an error stating that i ...

Ensuring type safety in React using TypeScript

Within the code snippet below, I have specified that setLocale should be passed a value of type Locale through LocaleContextValue. However, why does the setLocale function not throw an error if no value is provided as a parameter? Even when I change it t ...

Don't forget to include the line 'import "reflect-metadata"' at the beginning of your entry point for Jest tests

As I work on developing an application using dependency injection with tsyringe, I came across a case where a service receives the repository as a dependency. Here is an example: import { injectable, inject } from 'tsyringe' import IAuthorsRepos ...

A programming element that is capable of accessing a data member, but mandates the use of a setter method for modifications

I am unsure whether I need a class or an interface, but my goal is to create an object with a member variable that can be easily accessed like a regular variable. For example: interface LineRange { begin: number; end: number; } However, I want th ...

Exploring Angular 2's nested navigation using the latest router technology

Is there a way to implement nested navigation in Angular? I had this functionality with the previous router setup. { path: '/admin/...', component: AdminLayoutComponent } It seems that since rc1 of angular2, this feature is no longer supported. ...

Encountering a "ReferenceError: global is not defined" in Angular 8 while attempting to establish a connection between my client application and Ethereum blockchain

I'm trying to configure my web3 provider using an injection token called web3.ts. The token is imported in the app.component.ts file and utilized within the async ngOnInit() method. I've attempted various solutions such as: Medium Tutorial ...

What is the best way to loop through an array that contains a custom data type

When I declared the type: export interface Type{ id: number; name: string; } I attempted to iterate over an array of this type: for(var t of types) // types = Type[] { console.log(t.id); } However, I encountered the following error message: ...

Connecting multiple TypeScript files to a single template file with Angular: A comprehensive guide

Imagine you are working with a typescript file similar to the one below: @Component({ selector: 'app-product-alerts', templateUrl: './product-alerts.component.html', styleUrls: ['./product-alerts.component.css'] }) expo ...

Distributing a library of components using Vite, Vue 3, and Typescript to npm

My current challenge involves publishing a Vue 3 component library with Vite, all written in Typescript. The issue I'm facing is that the type definitions are not being included in the package when imported into another project. Upon importing the co ...

Dealing with GraphQL mutation errors without relying on the Apollo onError() function

When managing access to an API call server-side, I am throwing a 403 Forbidden error. While trying to catch the GraphQL error for a mutation, I experimented with various methods. (Method #1 successfully catches errors for useQuery()) const [m, { error }] ...

Invoke a function once a series of functions have finished executing in Angular 8

As a beginner in Angular, I am facing a challenge in calling a function after a series of functions have completed their execution. Although I don't require these functions to run sequentially, I do need to trigger another function once all of these f ...

Utilizing a conditional ngIf statement in HTML or incorporating a variable within typescript for logical operations

When working with our application, we often need to display or hide a button based on specific logic. Where do you think it is best to define this logic and why? In HTML: *ngIf='logic goes here' //Or *ngIf='someBoolean' and in Type ...

A convenient utility for generating React components with pre-populated Tailwind CSS classes

When it comes to extracting local Tailwind-styled components, I tend to do it like this: const Container: React.FC = ({ children }) => ( <div className="bg-white px-5 py-5"> {children} </div> ); To simplify this process, I ...

To populate an Ionic list with items, push strings into the list using the InfiniteScroll feature

Looking for help with implementing infinite scroll in a list? I am using the ion-infinite-scroll directive but struggling to push string values into my list. The list contains names of students in a classroom. Can anyone provide guidance on how to push str ...

Python: Converting a list of dictionaries into a nested dictionary

I have a large dataset in the form of a list of dictionaries that I want to reformat into nested dictionaries. However, I am unsure of how nested dictionaries work. I attempted to add the code I have tried, but encountered errors when posting it. Unfortuna ...