[英]Nullity guard doesn't work for inside forEach loop
In the below code, the second guard can't assert non-nullity of ab.cv
inside the forEach
loop, where uncommenting a local identical guard makes it work.在下面的代码中,第二个守卫不能在forEach
循环内断言ab.cv
的非空性,其中取消注释本地相同的守卫使其工作。 Why is it so?为什么会这样?
type B = {|
bv: B[],
cv: ?number
|}
let ab: B = {bv: [], cv: 1}
if (ab.cv) { // First guard
const a = ab.cv + 1 // Works
}
var a2;
if (ab.cv) { // Second guard
ab.bv.forEach(b => {/*if (ab.cv) */a2 = ab.cv + 1}) // Doesn't work except if uncommented
// Cannot perform arithmetic operation because null or undefined [1] is not a number.
}
Flow invalidates refinement done before forEach
callback. Flow 使在forEach
回调之前完成的细化无效。 Callback is considered a function call and any function call invalidates the refinement.回调被认为是 function 调用,任何 function 调用都会使细化无效。 More info on this in docs and faq 文档和常见问题解答中有关此的更多信息
One way to get around this is storing checked value in local variable:解决此问题的一种方法是将检查值存储在局部变量中:
const cv = ab.cv;
var a2;
if (cv) {
ab.bv.forEach(b => {a2 = cv + 1})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.