【问题标题】:Flow: why does it complain about string being null / undefined?流程:为什么它抱怨字符串为空/未定义?
【发布时间】:2018-10-19 04:01:10
【问题描述】:

我仍在尝试掌握 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].

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

【问题讨论】:

    标签: flowtype


    【解决方案1】:

    Flow 不会跟踪您分配的内容。它只跟踪变量的类型。而您正试图将类型?string 传递给string,这不是一个有效的分配,因为它可能是null。你知道它不为空,但 flow 不为空,因为它实际上并没有执行你的代码。

    很难为您提供解决方法的好建议,因为const text: ?string = 'Hello World!'; 是一个非常人为的示例,但您可以使用refinement 仅在text 已针对非空值进行测试时调用say .

    const text: ?string = 'Hello World!';
    if (text) {
      say(text);
    }
    

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

    let a: ?string = 'foo'
    let b = a; // flow infers the type of b as ?string
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-29
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      相关资源
      最近更新 更多