Patrick Patrick - 5 months ago 132
Javascript Question

TypeScript Map: how to use strong types?

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?

Answer

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}>();
Comments