Flow:为什么它会抱怨字符串为空/未定义?

wiz*_*bcn 4 flowtype

我仍在尝试掌握 Flow 的工作原理,谁能解释一下为什么这个简单的示例会引发错误?

function say(text: string) {
  console.log(text);
}

say('Hello World!'); // This is alright

const text: ?string = 'Hello World!';
say(text); // Error:(219, 5) Cannot call `say` with `text` bound to `text` because null or undefined [1] is incompatible with string [2].
Run Code Online (Sandbox Code Playgroud)

我知道,文本变量可以为空,但是当我调用 say(text) 时,它显然不是空的。

Ale*_*yne 5

Flow 不会跟踪您分配给什么内容。它只跟踪变量的类型。并且您正在尝试将类型传递?stringstring,这不是有效的分配,因为它可能是null. 您知道它不是 null 但 flow 不是,因为它实际上并没有执行您的代码。

这是很难给你很好的建议的解决方法,因为const text: ?string = 'Hello World!';是一个很做作的例子,但你可以用一个细化,只调用say如果text一个非空值已通过测试。

const text: ?string = 'Hello World!';
if (text) {
  say(text);
}
Run Code Online (Sandbox Code Playgroud)

唯一的时间流确实跟踪您分配的是隐式类型的变量初始化。但这只是将右手表达式的类型指定为变量的类型。

let a: ?string = 'foo'
let b = a; // flow infers the type of b as ?string
Run Code Online (Sandbox Code Playgroud)