Search code examples
typescriptdictionarykeyvaluepair

Object as Map Key in Typescript


I wanted to create a Map object with an object as key and a number as value in Typescript. I defined the map object as follows:

myMap: Map<MyObj,number>;
myObj: MyObj;

and when I try to add a pair to this map object:

this.myMap[myObj]=1;

It tells me that TS2538 Type 'MyObj' cannot be used as an index type. Is this possible in Typescript?


Solution

  • You have to use the set function e.g.

    this.myMap.set(myObj, 1);