Flow 中默认参数的问题

Trouble with defaulting arguments in Flow

我们的代码库卡在 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 类型,并保持版本不变?

对我来说这看起来像是一个 Flow 错误,所以如果更新不是一个选项,那么你唯一的选择似乎是不对对象模式使用默认分配,而赞成之后手动进行,例如

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

考虑到 Flow 团队很少能够专注于非 Facebook 使用,我肯定会优先更新到更新版本的 Flow,或者最近甚至考虑迁移到 TS。