Say the array is const items = [{category:'cat1', name:'name1'},{category:'cat2', name:'name2'}].
I want to construct the above array to become an object format like the following:
{
'cat1':'name1',
'cat2':'name2'
}
Without typescript, I can do the following to solve the problem:
const parseFunction = (items) => {
const newObj = {};
for (const item of items) {
newObj[item.category] = newObj[item.name];
}
return newObj;
}
However with typescript below:
interface IItems{
category: string,
name: string
}
interface INewObj{
'cat1': string,
'cat2': string
}
const parseFunction = (items: IItems[]) => {
const newObj = {} as INewObj;
for (const item of items) {
newObj[item.category] = newObj[item.name];
}
return newObj;
}
The line newObj[item.category] = newObj[item.name] throws the following TS error
Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'IQuotaByCategory'.
No index signature with a parameter of type 'number' was found on type 'IQuotaByCategory'.ts(7053)
How should I fix this?