Object distribution operator in a stream

I want to copy an object by changing only one property. Without a thread, I could do this using the object distribution operator as follows:

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 as follows:

 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 can I achieve this type of operation in a safe way in a thread?

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

 p2 = { p1 | y = 5 } 

There should be some equivalent in the stream.

+5
source share
3 answers

If you (really) need a class instead of the type alias, you can mimic the syntax Elm p2 = { p1 | y = 5 } p2 = { p1 | y = 5 } , specifying a constructor with 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}) 
+2
source

When you use object distribution, you are not getting an exact copy of the object. Instead, you get a simple object with all the original objects copied. So, Flow is here, p2 not Point . Try instead:

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

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

+3
source

Source: https://habr.com/ru/post/1258181/


All Articles