flowtype如何使用可选字段注释联合 [英] flowtype how to annotate union with optional fields

查看:73
本文介绍了flowtype如何使用可选字段注释联合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何实现以下流程

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中,可选字段和可为空的值之间存在差异.

  1. {key: ?valueType}表示对象必须包含key,并且其值必须为null 或类型为valueType. p>

  2. {key?: valueType}表示对象可能包含key,如果存在key,则其值必须为valueType类型.

  3. {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.

  1. {key: ?valueType} means the object must contain key, and its value must be either null or of type valueType.

  2. {key?: valueType} means the object might contain key, and if key is present, its value must be of type valueType.

  3. {key?: ?valueType} means the object might contain key, and if key is present, its value must be either null or of type valueType.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆