Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
Cómo hacer cumplir el tipo de datos de la clave y el valor en el mapa en JS

Digamos que estoy creando un map como este:

 let myMap = new Map();

Sabemos que tanto la key como el value pueden ser de cualquier tipo. Pero tengo un requisito en el que necesito aplicar Integer para la clave y String para el valor.

Por ejemplo:

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

Cualquier intento de violar esta regla debe verificarse en el momento de la compilación. Pero recibo errores de sintaxis cuando trato de hacer algo similar:

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

Por favor ayuda.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

En Typescript, puede usar:

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

Desafortunadamente, no puede hacer este tipo de verificación en Javascript.

about 4 years ago · Juan Pablo Isaza Report

0

Javascript no tiene un solo number de tipo integer . Por lo tanto, necesitaría definirlo así.

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

Puede definir un setter en el que valide la clave así

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

0

Javascript en sí mismo no proporciona ninguna sintaxis para admitir clases genéricas

Puede intentar escribir usando esta clase a continuación, que extiende 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) } }

Luego use Map2 en lugar de Map normal, con tipos en el constructor. Como esto,

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!