我想在仅更改单个属性时复制对象.没有Flow,我可以使用对象扩展运算符这样做:
class Point { x: number = 10; y: number = 10; }
const p1 = new Point();
const p2 = {...p1, y: 5};
Run Code Online (Sandbox Code Playgroud)
但是当我向p1和p2添加类型注释时,如下所示:
const p1 = new Point();
const p2 = {...p1, y: 5};
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
11: const p2:Point = {...p1, y: 5};
^^^^^^^^^^^^^ object literal. This type is incompatible with
11: const p2:Point = {...p1, y: 5};
^^^^^ Point
Run Code Online (Sandbox Code Playgroud)
如何在Flow中以类型安全的方式实现这种类型的操作?
举个例子,在Elm中,我可以这样做:
p2 = { p1 | y = 5 }
Run Code Online (Sandbox Code Playgroud)
Flow中必须有一些等价物.
使用对象传播时,不会获得对象的精确副本。相反,您将获得一个复制了所有源对象属性的普通对象。因此,Flow就在这里,p2不是Point。尝试以下方法:
type Point = { x: number, y: number };
const p1: Point = { x: 10, y: 10 };
const p2: Point = { ...p1, y: 5 };
Run Code Online (Sandbox Code Playgroud)
如果您(确实)需要别名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})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2152 次 |
| 最近记录: |