'Type alias in Flow that's equivalent to "An array of dictionaries"

If my data is:

[
    {
      key1: true,
      key2: "value1"
    },

    {
      key1: false,
      key2: "value2"
    },
  ];

What kind of custom flow type should I declare that conforms to it?

type MyType = // .... ?


Solution 1:[1]

To define the type of data, you can use Array<MyType> type where MyType is the type of elements in the array.

You can define the type alias MyType for the objects in the array using exact object types.

Remember that exact object types are the opposite of explicit inexact object types, which we discussed in your other question. This means that objects of type MyType must explicitly only have the keys key1: boolean and key2: string.

Here's the full Flow annotation:

/* @flow */

/**
 * @typedef {Object} MyType an exact object type with two keys
 * @see {@link https://flow.org/en/docs/types/objects/#toc-exact-object-types}
 * @property {boolean} key1
 * @property {string} key2
 */
type MyType = {|
    key1: boolean,
    key2: string,
|}

/**
 * @type {Array<MyType>}
 */
const data: Array<MyType> = [
  {
    key1: true,
    key2: "value1"
  },
  {
    key1: false,
    key2: "value2"
  },
]

If you want to alias a type for data as well, then you can define it as such:

/* @flow */

/**
 * @typedef {Object} MyObjectType an exact object type with two keys
 * @see {@link https://flow.org/en/docs/types/objects/#toc-exact-object-types}
 * @property {boolean} key1
 * @property {string} key2
 */
type MyObjectType = {|
    key1: boolean,
    key2: string,
|}

/**
 * @typedef {Array<MyObjectType>} MyType array type for an array of objects pf type "MyObjectType"
 * @see {@link https://flow.org/en/docs/types/arrays/#toc-array-type}
 * @todo alternatively can be defined as "type MyType = MyObjectType[]"
 */ 
type MyType = Array<MyObjectType>

/**
 * @type {Array<MyType>}
 */
const data: MyType = [
  {
    key1: true,
    key2: "value1"
  },
  {
    key1: false,
    key2: "value2"
  },
]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sbolel