flowtype如何使用可选字段注释联合 [英] flowtype how to annotate union with optional fields
问题描述
如何实现以下流程
export type Response = {
err: string,
data: ?Array<Object>,
} | {
data: Array<Object>,
};
我想表达一个类型,该类型返回错误和可选数据,或者在没有错误的情况下不返回错误字段.但是,我将其用作
return { err: 'todo' };
^^^^^^^^^^^^^^^ object literal. This type is incompatible with
.... Response
union: object type(s)
在Flow中,可选字段和可为空的值之间存在差异.
-
{key: ?valueType}
表示对象必须包含key
,并且其值必须为null
或类型为valueType
的. p> -
{key?: valueType}
表示对象可能包含key
,如果存在key
,则其值必须为valueType
类型. -
{key?: ?valueType}
表示对象可能包含key
,并且如果存在key
,则其值必须为null
或键入valueType
.
您的用例需要#2或#3.我个人建议不要使用#3 –我发现该模式比需要的更加灵活.
How to achieve the following in flow
export type Response = {
err: string,
data: ?Array<Object>,
} | {
data: Array<Object>,
};
I want to express a type, which returns an error and optional data or no error field in case there none. But, which I use it as
return { err: 'todo' };
^^^^^^^^^^^^^^^ object literal. This type is incompatible with
.... Response
union: object type(s)
In Flow, there is a difference between optional fields and nullable values.
{key: ?valueType}
means the object must containkey
, and its value must be eithernull
or of typevalueType
.{key?: valueType}
means the object might containkey
, and ifkey
is present, its value must be of typevalueType
.{key?: ?valueType}
means the object might containkey
, and ifkey
is present, its value must be eithernull
or of typevalueType
.
Your use case needs either #2 or #3. Personally I would recommend not using #3 – I find that pattern more flexible than it needs to be.
这篇关于flowtype如何使用可选字段注释联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!