在 Flow 中键入等效于 "An array of dictionaries" 的别名



如果我的数据是:

[
{
key1: true,
key2: "value1"
},
{
key1: false,
key2: "value2"
},
];

我应该声明哪种类型的自定义流类型符合它?

type MyType = // .... ?

要定义data的类型,可以使用Array<MyType>类型,其中MyType是数组中元素的类型。

您可以使用精确的对象类型为数组中的对象定义类型别名MyType

请记住,精确对象类型与显式不精确对象类型相反,我们在您的另一个问题中讨论了这个问题。这意味着类型MyType的对象必须显式地只有key1: booleankey2: string

以下是完整的 Flow 注释:

/* @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"
},
]

如果还想为data类型设置别名,则可以这样定义它:

/* @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"
},
]

相关内容

最新更新