代码之家  ›  专栏  ›  技术社区  ›  Justin808

如何解决“字符串与空或未定义的”流错误不兼容而无法赋值?

  •  1
  • Justin808  · 技术社区  · 7 年前

    我从flow中得到了一个错误,但我正在检查以验证错误永远不会发生。我怎么能告诉flow一切都好?

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

    这就是流程给我的错误。

    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]
    

    但从代码来看,我检查的测试不能为空或未定义。所以我不知道该怎么解决这个问题。

    Live Example Here

    2 回复  |  直到 7 年前
        1
  •  2
  •   Buggy    7 年前
    /* @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;} . ( + -只读)

        2
  •  0
  •   user10039288 user10039288    7 年前

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