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.
En Typescript, puede usar:
const myMap: Map<number, string> = new Map<number, string>();Desafortunadamente, no puede hacer este tipo de verificación en Javascript.
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 intJavascript 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