【问题标题】:Trouble with defaulting arguments in FlowFlow中默认参数的问题
【发布时间】:2021-07-09 07:39:28
【问题描述】:

我们的代码库停留在 flow-bin0.79.1 版本上,并且在此示例中使用默认参数似乎无法按预期工作:

function foo({a = 1}: {a: ?number}) {}

Playground link(请务必将版本设置为0.79.1

错误:

1: function foo({a = 1}: {a: ?number}) {}
                 ^ null or undefined [1] is incompatible with number [2].
References:
1: function foo({a = 1}: {a: ?number}) {}
                             ^ [1]
1: function foo({a = 1}: {a: ?number}) {}
                              ^ [2]

但是,从类型中删除 ? 是可行的。

function foo({a = 1}: {a: number}) {}

当使用最新版本的 Flow 时,两个示例都可以正常编译。

在我们的代码中,我们尝试默认为null

function foo({a = null}: {a: ?number}) {}

这似乎与第一个示例相同的原因失败了。

1: function foo({a = null}: {a: ?number}) {}
                 ^ null or undefined [1] is incompatible with number [2].

有没有办法解决此错误,同时将值默认为 null,将该值注释为 Maybe 类型,并保持版本不变?

【问题讨论】:

  • 如果在函数体中使用if (a === undefined) a = 1; 代替= 1 是否可以接受?似乎默认是问题的核心,使用该语法的唯一好处是它有点短。
  • 好点,是的,这是可以接受的

标签: flowtype


【解决方案1】:

这对我来说似乎是一个 Flow 错误,所以如果更新不是一个选项,那么您唯一的选择似乎是不对对象模式使用默认分配,而是在之后手动执行此操作,例如

function foo({a}: {a: ?number}) {
  if (a === undefined) a = 1;
  // ...
}

考虑到 Flow 团队几乎无法专注于非 Facebook 的使用,我肯定会优先更新到更新版本的 Flow,或者这些天甚至考虑迁移到 TS。

【讨论】:

  • 我们刚刚了解到这个错误似乎仅限于默认的解构参数。例如,这适用于0.79.1function foo(obj: {a: ?number} = {a: 1}) {}
猜你喜欢
  • 1970-01-01
  • 2010-10-22
  • 2012-12-03
  • 1970-01-01
  • 1970-01-01
  • 2019-01-14
  • 1970-01-01
  • 2017-11-15
  • 2011-12-24
相关资源
最近更新 更多