My work frequently involves arrays structured like this:
[
{key1: val1, key2: value2, key3: val3},
{key1: val1, key2: value2, key3: val3},
{key1: val1, key2: value2, key3: val3}]
and I often need to convert them into a dictionary/map format, for example:
[val1FromFirstElement]: {key2: val2, key3, val3},
[val1FromSecondElement]: {key2: val2, key3, val3},
[val1ThirdElement]: {key2: val2, key3, val3}}
I usually use a reduce method, but it can make the code look cluttered. I am looking to create a versatile helper function that ensures the array being mapped has the specified key (in this case, key1).
function toDictionary<T, Key extends keyof T> (array: T[], key: Key) {
return array.reduce((prev, cur: T) => {
return{...prev, ...{[cur[key]]: cur}};
}, {})
}
The issue arises when using [cur[key]]
, as it results in a compile error stating
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
I understand that index access types are limited to number | string | symbol
, but I don't see why I should have to specify any other type since TypeScript should already know that keys can only be one of these types. Am I missing something?
I'm hopeful that someone can enlighten me on where my misunderstanding lies.