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.
CodePudding user response:
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
CodePudding user response:
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.
CodePudding user response:
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