Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object spread operator in Flow

Tags:

flowtype

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

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

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

I get the following error:

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

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 }

There must be some equivalent in Flow.

like image 971
Dave Ford Avatar asked Oct 13 '16 23:10

Dave Ford


2 Answers

When you use object spread, you don't get an exact copy of an object. Instead, you get a plain object with all source object's properties copied. So, Flow is right here, p2 is not Point. Try this instead:

type Point = { x: number, y: number };
const p1: Point = { x: 10, y: 10 };
const p2: Point = { ...p1, y: 5 };
like image 188
vkurchatkin Avatar answered Oct 07 '22 19:10

vkurchatkin


Explanation: class does not work because it uses nominal typing but type works because that uses structural typing.

like image 23
jhegedus Avatar answered Oct 07 '22 18:10

jhegedus