流类型 - 数组的对象

时间:2018-03-06 10:58:26

标签: javascript flowtype

我有这样的对象:

{
  one: [
    {
      a: "some",
      b: "some",
    }
  ],
  two: [
    {
      a: "some",
      b: "some",
    }
  ],

  ...
}

此示例的正确类型是什么?

1 个答案:

答案 0 :(得分:2)

你去了

/* @flow */


type MyType = {
  [key: string]: Array<{ a: string, b: string }>,
};

function myFunc(obj: MyType) {
  return obj;
}


const myObj = {
  one: [
    {
      a: 'some',
      b: 'some',
    }
  ],
  two: [
    {
      a: 'some',
      b: 'some',
    }
  ],
};

const doSomething = myFunc(myObj); // No errors

Live demo

文档:

Objects as maps doc中,您会发现For objects like these, Flow provides a special kind of property, called an “indexer property.” An indexer property allows reads and writes using any key that matches the indexer key type.使用专用的语法:{ [user_id: number]: string }