Flow 中的对象传播运算符

Object spread operator in Flow

我想复制一个对象,同时只更改一个 属性。没有 Flow,我可以像这样使用对象展开运算符来做到这一点:

class Point { x: number = 10; y: number = 10; }
const p1 = new Point();
const p2 = {...p1, y: 5};

但是当我像这样向 p1 和 p2 添加类型注释时:

const p1 = new Point();
const p2 = {...p1, y: 5};

我收到以下错误:

 11: const p2:Point = {...p1, y: 5};
                      ^^^^^^^^^^^^^ object literal. This type is incompatible with
 11: const p2:Point = {...p1, y: 5};
          ^^^^^ Point

我如何在 Flow 中以类型安全的方式实现这种类型的操作?

例如,在 Elm 中,我可以这样做:

p2 = { p1 | y = 5 }

Flow 中一定有一些等价物。

当您使用对象传播时,您不会获得对象的精确副本。相反,您会得到一个复制了所有源对象属性的普通对象。所以,Flow 就在这里,p2 不是 Point。试试这个:

type Point = { x: number, y: number };
const p1: Point = { x: 10, y: 10 };
const p2: Point = { ...p1, y: 5 };

如果您(真的)需要一个 class 而不是 type 别名,您可以通过定义一个只有一个参数的构造函数来模拟 Elm 语法 p2 = { p1 | y = 5 }

export class Point {
  x: number = 10;
  y: number = 10;
  constructor(fields?: { x: number, y: number }) {
    Object.assign(this, fields)
  }
}
const p1 = new Point()
const p2: Point = new Point({...p1, y: 5})

解释:class 不起作用,因为它使用了 nominal typing,但 type 起作用,因为它使用了结构类型。