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?
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?
1 Answer
Reset to default 19You need to provide generic types information to the created Map
like this:
let oMap:Map<string,{name:string,price:number}> = new Map<string,{name:string,price:number}>();
And after that you can omit the type declaration, leaving the job to the compiler:
// oMap is correctly inferred to be Map<string,{name:string,price:number}>
let oMap = new Map<string,{name:string,price:number}>();
new Map
). – BeetleJuice Commented Jun 18, 2016 at 20:47