Home > database >  Element implicitly has 'any' type because expression of type 'any' can't be
Element implicitly has 'any' type because expression of type 'any' can't be

Time:10-18

I want to have an object that's indexed by an id of type string and has a value of a string.

Here's my interface:

interface Bars {
  [id: string]: string;
}

the bars objects seen below is an array of objects where the keys are a string (barId) and string value (myVal) in the reducer.

const bars = barsResponse.bar.reduce((acc, bar) => {
    acc[bar.barId as string] = bar.myVal;
    return acc;
  }, {});

What am I doing wrong here that TypeScript is shouting:

Element implicitly has 'any' type because expression of type 'any' can't be used to index type '{}'

CodePudding user response:

You will have to assign a type to the accumulator parameter or the default return value

reduce((acc:Bars, bar) => {...}

const bars = bar.reduce((acc, bar) => {
  acc[bar.barId as string] = bar.myVal;
  return acc;
}, {} as Bars);
  • Related