【发布时间】:2021-07-09 07:39:28
【问题描述】:
我们的代码库停留在 flow-bin 的 0.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