如何解决“因为字符串与null或未定义不兼容而无法分配”流错误?

时间:2018-10-11 22:37:12

标签: flowtype

我从流程中得到一个错误,但是我正在检查以确保该错误永远不会发生。我怎样才能告诉流程一切正常?

/* @flow */

type A = {|
 test: string;
|}

type B = {|
 test: ?string;
|}

function foo(b: B): A {
  if (b && b.test) {
    return {
      test: b.test
    };
  }

  return { test: 'hi' };
}

const test: B = foo({ test: 'a' });

这是Flow给我的错误。

21: const test: B = foo({ test: 'a' });
                    ^ Cannot assign `foo(...)` to `test` because string [1] is incompatible with null or undefined [2] in property `test`.
References:
4:  test: string;
          ^ [1]
8:  test: ?string;
          ^ [2]

但是从代码中,我正在检查测试不能为null或未定义。因此,我不确定如何解决此问题。

Live Example Here

2 个答案:

答案 0 :(得分:1)

best_params_

这是因为/* @flow */ type A = {| test: string; |} type B = {| test: ?string; |} declare var TestA: A; declare var TestB: B; TestB = TestA; // ^ Cannot assign `TestA` to `TestB` because string [1] is incompatible with null or undefined [2] in property `test` 不是{|test: string;}的子类型,所以我们可以更改{|test: ?string;},但也可以更改TestB.test = null,其中TestA不应为空。

test{|test: string;}的子类型。 ({| +test: ?string;}-只读)

答案 1 :(得分:0)

语法错误。我相信这是正确的代码。

/* @flow */

type A = {|
 test: string;
|}

type B = {|
 test: string;
|}

function foo(b: ?B): A {
  if (b && b.test) {
    return {
      test: b.test
    };
  }

  return { test: 'hi' };
}

const test: B = foo({ test: 'a' });