【问题标题】:Understanding an intersection of function types in flow了解流中函数类型的交集
【发布时间】:2019-08-24 11:05:42
【问题描述】:

寻找了解静态类型检查器流程的人向我解释我在哪里走错了路。我试图理解子类型函数的交集。

我知道对函数进行子类型化需要逆变输入和协变输出,但似乎这并不能解决所有问题。

举个例子

type InterT = ((number) => string) & ((string) => number);

通过简单的测试,这似乎归结为(number & string) => number | string。有效的子类型包括

declare var I: InterT;

declare var test1: ((number) => number | string) => void;
test1(I); // works

declare var test2: ((string) => number | string) => void;
test2(I); // works

declare var test3: ((number & string) => number) => void;
test3(I); // works

declare var test4: ((number & string) => string) => void;
test4(I);

declare var test5: ((number | string) => number | string) => void;
test5(I); // works 

declare var test6: ((number | string) => string) => void;
test6(I); // FAILS 

declare var test7: ((number | string) => number) => void;
test7(I); 

为什么最后两种情况都失败了? string <: number | stringnumber <: number | string,对吗?

【问题讨论】:

    标签: javascript facebook flowtype


    【解决方案1】:

    Flow 中的交叉点类型似乎“严重损坏”(https://github.com/facebook/flow/issues/6482#issuecomment-421167167)。我无法解释为什么 test6test7 会失败,但我想指出 number & string 类型是“不可能的”类型 (https://flow.org/en/docs/types/intersections/#toc-impossible-intersection-types)。来自文档:

    // @flow
    type NumberAndString = number & string;
    
    function method(value: NumberAndString) {
      // ...
    }
    
    // $ExpectError
    method(3.14); // Error!
    // $ExpectError
    method('hi'); // Error!
    

    我们观察到numberstring 都不能满足number & string。因此,老实说,我不明白为什么test1test2 会满足(number & string) => number | string 类型。我希望清楚地了解交叉点类型在 Flow 中的作用(或应该)如何。不过,就目前而言,由于它们的破坏性,它们似乎不实用。

    【讨论】:

      猜你喜欢
      • 2019-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      相关资源
      最近更新 更多