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
TPropertyas never, yet it correctly identifies theTArraytype. Why is this happening?the way how this is written at the moment, the returned
Mapis set to have keys of theTPropertyvalue, but instead of that, I would need keys typed as the type of theTPropertyfrom the object. I tried withtypeof TPropertybut 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