首页 文章

如何解决'Cannot assign because string is incompatible with null or undefined'流量错误?

提问于
浏览
1

我从流程中收到错误,但我正在检查以确认错误永远不会发生 . 我怎么能告诉流程一切正常?

/* @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
    /* @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

    语法错误 . 这是我相信的更正代码 .

    /* @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' });
    

相关问题