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?
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.
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.
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}>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With