What is the best way to retrieve an object based on a custom key type in TypeScript when using a

I have a custom class called Foo:

class Foo {
    constructor(public v: any) {
    }
}

And I have a map where Foo is my Key:

const map = new Map<Foo, string>();

As far as I know, TypeScript does not support comparison overloading. How can I ensure that retrieving the key works correctly?

const foo = new Foo(1234);
map.get(foo);

Below is the full code snippet:

class Foo {
    constructor(public v: any) {

    }
}

const map = new Map<Foo, string>();

const foo = new Foo(1234);
map.set(foo, "HELLO WORLD");

const foo2 = new Foo(1234);
console.log(map.get(foo2)); // This will not work

console.log(map.get(foo)); // This will work correctly

You can view my issue here: Link to Issue

Answer №1

Your issue does not stem from TypeScript, but rather from JavaScript lacking referential transparency. This is why a comparison like new Foo(123) === new Foo(123) will always return false.

Resolve

The JavaScript Map has a somewhat restricted API. If you need to locate a specific entry using a custom comparison function (such as comparing by value), my suggestion would be to utilize the .entries() method to retrieve all entries from the Map in the form of an array of tuples [key, value][]. From there, you can use Array.find() to locate the desired entry. The Map itself lacks such functionality.

Alternatively, it may be beneficial to reconsider your data structure. Given the limitations of the Map, using a primitive data type as a key could prove more effective. Without knowing the specifics of your situation, this is a general suggestion I can provide.

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

Is there a way in Selenium to determine the type of tag associated with the element we are trying to locate?

Is there a way in Selenium to determine the type of tag? On my automation page, some fields may change their type. For example, if the first field value is greater, the second field becomes an input text; if the first is "IN", then a dropdown appears. So, ...

Guide on converting a JSON object into a TypeScript Object

I'm currently having issues converting my JSON Object into a TypeScript class with matching attributes. Can someone help me identify what I'm doing wrong? Employee Class export class Employee{ firstname: string; lastname: string; bi ...

Disable functionality not functioning properly on button attribute

I've created a demo on JSFiddle here: http://jsfiddle.net/qJdaA/2/. The goal of this code is to disable the button with the ID #monitor if no checkboxes are checked. var checked = $('#status_table tr [id^="monitor_"]:checked'); if (checked. ...

Leverage the version attribute within package.json within one of its scripts

Is there a way to access the version attribute of my package.json file within one of its scripts? I want to include the version number in the name of the JS bundle, instead of using a hash as an identifier. This is what I currently have: "build-js": "bro ...

Using `reduce` in TypeScript, you can organize an array of objects based on a shared property

Here is an example of an array: [ { id: '1', task: 'Grocery shopping', isImportant: true }, { id: '2', task: 'Meeting', isImportant: false }, { id: '3', task: &apos ...

Issue: (SystemJS) the exports variable is not defined

In the process of developing a .net core mvc + angular application, I encountered an interesting situation. The MVC framework handles user management, and Angular takes over when users navigate to specific areas of the application. Initially, I integrated ...

Comparing Angular 5 with --aot and Angular 5 with --aot=false configuration settings

I am having an issue with my Angular application using Angular 5.0.0 and rxjs ^5.5.2. When I run the command ng serve --aot=false, everything works fine. However, when I use ng serve --aot, I encounter the following error: core.js:1350 ERROR Error: Uncaug ...

The VueJS app seems to be experiencing difficulties with rendering the content

Just starting out with VueJS and I have my initial files - index.html and index.js. I want to stick with just these two files and not add any more. Here's the content of index.html: <html lang="en"> <head> <meta charset ...

Is it possible for me to create an If statement that can verify the current index within a Map?

I have the following TypeScript code snippet: export default class SingleNews extends React.Component<INews, {}> { public render(): React.ReactElement<INews> { return ( <> {this.props.featured ...

Error message with ThreeJS ObjectLoader: "unable to interpret the 'fog' property as it is not defined"

Currently, my setup involves using ThreeJS to import a scene as shown in the code snippet below: $(document).ready(function(){ var scene = new THREE.ObjectLoader().load("scene.js"); var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / ...

Determine which file to load based on the size of the browser

I have a quick question regarding the correct syntax. I am trying to only load the jQuery file if the browser screen width is less than 1100px. <script type="text/javascript"> $(document).ready(function() { if ($(window).width() < 1100) { ...

Enhancing React components with dynamic background colors for unique elements

I am encountering an issue while using a map in my code. Specifically, I want to set the background of a particular element within the map. The element I am referring to is "item .title". I aim for this element to have a background color like this: https:/ ...

Executing TypeScript functions in a sequential order within an Angular2 environment

Here is a Typescript function I have written: AdjustSpinAndGetAmbiguityAnalysisResult() { this.cssRefreshSpin = "glyphicon glyphicon-refresh glyphicon-spin"; this.GetAmbiguityAnalysisResult(); this.cssRefreshSpin = "glyphicon glyph ...

Asynchronous Return in NodeJS Class Methods

Currently, I am in the process of developing a JavaScript class that includes a login method. Here is an overview of my code: const EventEmitter = require('events'); const util = require('util'); const Settings = require('./config ...

The concept of 'this' in TypeScript classes compared to JavaScript's scope

Is there a way to change the custom icon of a video when it is toggled between Play and Pause? ngAfterViewInit() { const vdoCont = document.querySelector('.video-player'); const vdo = vdoCont.querySelector('video'); vdo.addEventL ...

Switch between display modes using a button and CSS media query

I'm trying to find the most effective method for toggling display states on a webpage using a button while also being able to adjust based on screen size. For larger screens, I want to default to a horizontal layout with the option to switch to vertic ...

Issue with shadows on imported OBJ objects in Three.js when material is applied

After importing an obj using this load function: // triggered when the resource is loaded function ( obj ) { // For any meshes in the model, add our material. obj.traverse( function ( element ) { if ( element instance ...

Using conditional subscriptions in Meteor at the template level

When working with the same template in different routes using a conditional publication method, I encountered an issue where the data was not being subscribed to as expected. The console log returned an empty array. server/publication.js Meteor.publish(& ...

Try implementing transform translate with absolute coordinates when positioning elements on a webpage

If I wanted to create a box that moves along with the mouse cursor, I could achieve that using the code below. document.addEventListener('mousemove', (e) => { document.documentElement.style.setProperty('--mouse-x', e.clientX ...

JavaScript has encountered an Uncaught TypeError due to an illegal invocation

I am currently developing a lambda function that calls another function with specific parameters. While this code runs without issues in Firefox, it encounters an error in Chrome, displaying a strange message in the inspector: Uncaught TypeError: Illegal ...