Flow error property is missing in object literal [1] when using reduce to create a dictionary from an array

326 views Asked by At

I'm trying to use reduce to create a dictionary from an array. However I run into a flow error property is missing in object literal [1] when using reduce to create a dictionary from an array. This happens for all three keys 'A', 'B', and 'C'.

  const foo = [
    'A',
    'B',
    'C',
  ];

  const bar = foo.reduce((acc, curr) => {
 
    // the actual code will do some logic on the string value in foo
    // but for the test just create a dictionary of the key to itself as value

    acc[curr] = curr;
    return acc;
  }, {});

https://flow.org/try/#1N4Igxg9gdgZglgcxALlAJwKYEMwBcD6aArlLnALYYrgA2WAzvXGCADQgYAeOBARgJ74AJhhhYiNXClzEM7DFCLl602QF92kEdQA6UAAT7IUern0wIEfQF59AbT2HDAcgCCz1o6fOAQh68uAML+BvoAugDcel7Gpvq8WGg25pYAdJhCRGAYABQ5OGCsRkRoaACUNgB8+sCOAfoA9A36uAAWGPo8RFg0RhAi+gDucDS9Qlb0EJT6NJYA1kQADvrQKRD1TfFEZhZJbR24GHEAVkRxYJhYh536Qsxk0In8KzAt7fpzGM+4VnC49BgaK8GPoAG49IgYaKhQwFOxgEpoMLJBGlKIw-SYXAlAwFdGGDQ1NRlCJsECgjBoJjQaiggAMqQATHSACypOkgNRAA

1

There are 1 answers

1
Plagiatus On

The problem here is that Flow recognizes the initial value {} as being just that - an empty object. So you trying to add something to {}.A throws the warning/error.

Here is a solution, giving the initial value a custom Dictionary type, see Objects as Maps:

interface Dictionary {
  [key: string]: any
}

const foo = ['A','B','C'];

let initial: Dictionary = {};
const bar = foo.reduce((acc, curr) => {
  acc[curr] = curr;
  return acc;
}, initial);

PS: This works the same in Typescript