Flow中的对象散布运算符 [英] Object spread operator in Flow

查看:41
本文介绍了Flow中的对象散布运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在仅更改单个属性的同时复制对象.没有Flow,我可以使用像这样的对象散布运算符来做到这一点:

I want to copy an object while changing only a single property. Without Flow, I could do this using the object spread operator like this:

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

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

But when I add type annotations to p1 and p2 like this:

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中如何以一种安全的方式实现这种类型的操作?

How would I achieve this type of operation in a type safe way in Flow?

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

As an example, in Elm, I can do this:

p2 = { p1 | y = 5 }

Flow中必须有一些等效项.

There must be some equivalent in Flow.

推荐答案

如果(确实)需要class而不是type别名,则可以通过定义仅包含一个的构造函数来模拟Elm语法p2 = { p1 | y = 5 }论点

If you (really) need a class instead of a type alias you can simulate the Elm syntax p2 = { p1 | y = 5 } by defining a constructor with only one argument

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})

这篇关于Flow中的对象散布运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆