javascript - Flow: Object type incompatible with Array<mixed> - Stack Overflow

I don’t understand the flow error I’m currently getting. I have a Javascript object of objects (dataObj

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:

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!

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:

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!

Share Improve this question asked Nov 8, 2017 at 18:38 user3802348user3802348 2,60211 gold badges38 silver badges51 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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]);
}

If you prefer to use Object.values() (probably more efficient) and have typing right, you can use a helper function like this:

 function objectToValues<A, B>(obj:{[key: A]: B} ): Array<B> {
    return ((Object.values(obj): any): Array<B>)
 }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744186432a4562226.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信