使用流相交两种类型的正确方法

Proper way to intersect two types using flow

我最近学习了如何在流中交叉类型。我很好奇有什么区别 在以下两种相交两种对象类型的方法之间:

说我有下面两种类型要相交。

type A = {
   foo: string
}

type B = {
   bar: boolean
}

我想将它们相交以创建一个看起来像这样的 C 型

type C = {
  foo: string,
  bar: boolean
}

方法一:

type C = A & B

方法二:

type C = {...A, ...B}

这些方法是否等效?

不,它们不等价。

起初,我想不出 & 有用的情况(因为它坏了)。我建议始终使用点差。

basic difference: spread makes all the properties optional if your type is non-exact. You can 使用 $Exact 实用程序修复它。

正确的做法是将所有类型声明为精确的。 Flow 有一个配置选项,它 will become a default behavior in the future. But & does not work 具有确切的类型,而 spread 有。

交集的结果是 often a broken 类型。