Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

101
Vistas
HashMap in TypeScript with custom object

Introduction

I am currently work in project that I need to save the score of each user. For this I used a Map<User, number> to represent it.

Problematic

If I create map with a user named john:

let myMap: Map<User, number> = new Map();
myMap.set(new User("John","Hasherman"), 0);

And if I want to set John Hasherman’s score to 1 (voluntarily using a new instance and not the one previously used), with this code:

myMap.set(new User("John","Hasherman"), 1);

But TypeScript create a new element inside myMap.

Question

So my question is, do you know if it’s possible to customize the comparator used inside the map? like Java when defining hashCode() and equals(o Object)?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You'll need a way for the User to expose functionality that will identify a particular user, perhaps by name, or perhaps by a more unique ID. Either way, a Map where each user is the key isn't very suited to the job, but it's possible.

class User {
    public first: string;
    public last: string;
    constructor(first: string, last: string) {
        this.first = first;
        this.last = last;
    }
}

const myMap: Map<User, number> = new Map();
myMap.set(new User("John","Hasherman"), 0);

// to set John's value to 1:
const foundJohn = [...myMap.keys()].find(
    obj => obj.first === 'John' && obj.last === 'Hasherman'
);
if (foundJohn) {
    myMap.set(foundJohn, 1);
}

It's somewhat convoluted. I'd suggest considering a different data structure if possible.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda