Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using strong typed Map

I'm having trouble strong typing my Map objects with typescript 1.8.10. Here is an excerpt from core-js defining the Map interface:

interface Map<K, V> {
    clear(): void;
    delete(key: K): boolean;
    forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
    get(key: K): V;
    has(key: K): boolean;
    set(key: K, value?: V): Map<K, V>;
    size: number;
}

I want to create a map that uses string keys and only ever stores values with the shape {name:string,price:number}. I tried declaring my object with:

let oMap:Map<string,{name:string,price:number}> = new Map();

However, the compiler throws error TS2322: Type 'Map<{}, {}>' is not assignable to type 'Map<string, { name: string; price: number; }>'. Is there a way to take advantage of strong typing when using ES6 Map objects in typescript?

like image 344
BeetleJuice Avatar asked Jun 18 '16 07:06

BeetleJuice


People also ask

How do you define a map type in TypeScript?

Use Map type and new keyword to create a map in TypeScript. let myMap = new Map<string, number>(); To create a Map with initial key-value pairs, pass the key-value pairs as an array to the Map constructor.

How do I change a map value in TypeScript?

Use the set() method to update a value in a Map , e.g. map. set('key', 'value') . The set() method adds or updates the element with the provided key and value and returns the Map object.


1 Answers

You need to provide generic types information to the created Map like that:

let oMap:Map<string,{name:string,price:number}> = new Map<string,{name:string,price:number}>();

And after that you can omit type declaration, leaving the job to compiler:

// oMap is correctly inferred to be Map<string,{name:string,price:number}>
let oMap = new Map<string,{name:string,price:number}>();
like image 53
zlumer Avatar answered Nov 10 '22 03:11

zlumer