Search code examples
javascriptflowtypeflow-typed

Flow: Object type incompatible with Array<mixed>


I don’t understand the flow error I’m currently getting. I have a Javascript object of objects (dataObject) that I want to convert to an array of objects, so I do so using Object.values(dataObject). Then, I iterate through each object in the array with the following:

  const dataObjectArray = Object.values(dataObject);
  return dataObjectArray((data: DataObject) => {
    const { typeA, typeB } = data;
    return {
      TYPE_A: typeA,
      TYPE_B: typeB,
    };
  });

But I get the following flowtype error:

flow error

I’m not sure how to match up the types. Currently my DataObject flow type is

type DataObject = {
    typeA: string,
    typeB: string,
};

Any help would be appreciated. Thanks!


Solution

  • The type definition for the Object.values function has no way to know that the argument passed to it is an object where the values are all the same type. You could just as easily be doing Object.values({foo: 4, bar: "str"}). The type definition is

    (any) => Array<mixed>
    

    meaning that you are doing .map on a value of type Array<mixed>.

    That means if you want to use it as object, your method will not work. Assuming your "object of objects" is typed as

    type DataObjects = {
      [string]: DataObject,
    }
    

    You'd likely be better off doing

    function values(objs: DataObjects): Array<DataObject> {
      return Object.keys(objs).map(key => objs[key]);
    }