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

196
Views
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 answers
Answer question

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 Report

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 Report

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 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!