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:
-
when I try to use the function, typescript implies
TProperty
as never, yet it correctly identifies theTArray
type. Why is this happening? -
the way how this is written at the moment, the returned
Map
is set to have keys of theTProperty
value, but instead of that, I would need keys typed as the type of theTProperty
from the object. I tried withtypeof 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.