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

197
Vistas
How to enforce datatype of key and value in map in JS

Let's say I'm creating a map like this:

let myMap = new Map();

We know that key and value both can be of any type. But I've a requirement where I need to enforce Integer for the key and String for the value.

For e.g.:

1 => 'Apple'
2 => 'Ball'
3 => 'Cat'

Any attempt to violate this rule should be checked at compile time itself. But I'm getting syntax errors when I try to do somewhat similar:

  let myMap = new Map<integer,string>();

Please help.

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

0

In Typescript, you can use:

 const myMap: Map<number, string> = new Map<number, string>();

Unfortunately you can't do this kind of check in Javascript.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Javascript dosn't have an integer type only number. Therefor you would need to define it like so.

 let myMap = new Map<number,string>();

You can define a setter in which you validate the key like so

Number.isInteger(data) // returns weither or not data is an int
about 4 years ago · Juan Pablo Isaza Denunciar

0

Javascript in itself doesn't provide any syntax to support generic classes

You can try writing using this class below, which extends Map.

class Map2 extends Map{

    constructor(keyType, valueType){
        super()
        this._keyType = keyType;
        this._valueType = valueType;
        
    }


    _matchesType(key,value){
        return (typeof(key) === this._keyType) && (typeof(value) === this._valueType);
    }


    set(key, value){
       if(!this._matchesType(key,value))
             throw 'Type Mismatch Exception';
       super.set(key,value)
    }

}

Then use Map2 instead of normal Map, with types in the constructor. Like this,

const m2 = new Map2('number', 'string');

m2.set(1,'apple');
m2.get(1); //returns 'apple'

m2.set('test', 'test value') // throws Type Mismatch Exception
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