类型声明中的传播算子在Flow中做什么?

时间:2019-03-03 18:07:47

标签: flowtype

如果我有两个部分匹配形状的对象,例如

const point2d = { x: 0, y: 0 };
const point3d = { x: 0, y: 0, z: 0 };

那么Flow中的有效类型声明将是

type Point2D = { x: number, y: number };
type Point3D = Point2D & { z: number };

起初,我尝试使用对象散布运算符并由于符号类似而很快遇到了问题

type Point3D = { ...Point2D, z: number };

被认为是有效的,但没有达到目标,因为最终x类型的yPoint3D属性都丢失了。

例如,我可以使用扩展符号来做到这一点(这是错误的):

type Point2D = { x: number, y: number };
type Point3D = { ...Point2D, z: number };

const point2d: Point2D = { x: 0, y: 0 };
const point3d: Point3D = { y: 0, z: 0 }; // No errors

但不能错过类型声明为交叉符号的对象声明中的x属性:

type Point2D = { x: number, y: number };
type Point3D = Point2D & { z: number };

const point2d: Point2D = { x: 0, y: 0 };
const point3d: Point3D = { y: 0, z: 0 }; // Cannot assign object literal to `point3d` because property `x` is missing in object literal [1] but exists in `Point2D` [2].

请注意,这两种情况都不是精确的形状。

在这种情况下,Flow的行为是否是故意的?我想念什么吗?

1 个答案:

答案 0 :(得分:0)

请参见this issue

简短的版本是您可以通过使对象精确来解决所有这些类型的问题。总的来说,我发现使对象类型成为精确对象时,您会更轻松地进行操作,除非您真的出于某种原因不希望它们精确。另外,$ReadOnly(如果适用)。 Try