最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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>)
 }
发布评论

评论列表(0)

  1. 暂无评论