如果我有两个部分匹配形状的对象,如
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
类型中缺少y
和Point3D
属性。
例如,我可以用扩散符号(这是错误的)来做到这一点:
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是否有意在传播符号的情况下?我错过了什么吗?
简短的版本是,您可以通过精确地使用对象来解决所有这些问题。一般来说,我发现使用对象类型的时候会更容易,除非你真的不希望它们因某些原因而准确。另外,$ReadOnly
适用。 Try