Typescript converting an array of objects to a Map

I have the following array:

const myArray = [{
   a: 'test',
   b: 1
}, {
   a: 'test1',
   b: 2

I would like to convert this array to a Map, based on one of it’s properties, and maintain a strongly typed code, with a function like this:

convertArrayToMap<TObject extends {}, TArray extends TObject[], TProperty extends keyof TObject>(inputArray: TArray, property: TProperty): Map<TProperty, TObject> {
   // ... logic goes here <-- I AM AWARE of the logical code, this is not what I need, I need help in typing my function

I am having two troubles with the typings here:

  1. when I try to use the function, typescript implies TProperty as never, yet it correctly identifies the TArray type. Why is this happening?

  2. the way how this is written at the moment, the returned Map is set to have keys of the TProperty value, but instead of that, I would need keys typed as the type of the TProperty from the object. I tried with typeof TProperty but typescript complains.

In general, here is an example, on how the function should work:

const map = convertArrayToMap(myArray, 'a'); // this should be a Map<string, { a: string, b: number}> type 
console.log(map.get('test').b); // this logs 1 on the screen

>Solution :

Try this one:

function convertArrayToMap<
  TObject extends object,
  TProperty extends keyof TObject,
  inputArray: TObject[],
  property: TProperty,
): Map<TObject[TProperty], TObject> {
  // ...

Here’s also a link to playground.

Leave a Reply