Patrick Patrick - 2 years ago 389
Javascript Question

TypeScript Map: how to use strong types?

I'm having trouble strong typing my

objects with
typescript 1.8.10
. Here is an excerpt from
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
. 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
objects in typescript?

Answer Source

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}>();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download