为什么函数的交集类型接受任何类型的声明而不是两者都接受?

zer*_*kms 5 javascript flowtype

我举了个例子

/* @flow */
class Foo {}
class Bar {}
declare var f: ((x: Foo) => void) & ((x: Bar) => void);
f(new Foo());
Run Code Online (Sandbox Code Playgroud)

来自文档页面https://flowtype.org/docs/union-intersection-types.html#_

此代码类型检查没有错误.

对我来说,结果并不是很明显.

因为它们显示在页面顶部附近的另一个例子:

/* @flow */
type I = {a: number} & {b: number};
var x: I = {a: 1, b: 2};
x = {a: 1, b: 2, c: "three"};
Run Code Online (Sandbox Code Playgroud)

交集(从术语语义本身流出)是2(或更多)类型的复合.基本上AND就是那些.

那么,为什么f(new Foo());类型检查不会失败呢?这个new Foo()论点显然不是一个实例,Bar所以不能通过.

我错过了什么?

UPD

经过一些更多的研究后,我发现使用时的意义|&交换declare var(对比type或就地输入).我找不到解释为什么它甚至发生在第一个地方.

Ala*_*ell 2

我可能误解了你的问题,但我希望它能进行类型检查。参数 ,new Foo()具有 type Foo,因此只要f具有 type ,应用程序就应该没问题Foo => ...。确实如此。(它有类型Bar => ...)。

相比之下,如果f有 type (x: Foo & Bar) => void,则不会进行类型检查,因为new Foo虽然肯定是 type Foo,但也不是 type Bar

对于另一个比较,如果f有 type ((x: Foo) => void) | ((x: Bar) => void),则不会进行类型检查。参数 ,new Foo具有 type Foo,尽管f可能具有 type Foo => void,但它也可能具有 type Bar => void