<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Maurice Reigman on Medium]]></title>
        <description><![CDATA[Stories by Maurice Reigman on Medium]]></description>
        <link>https://medium.com/@mauricereigman?source=rss-d891749bd19b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pIG02-nFJzKqaJX02aPuCA@2x.jpeg</url>
            <title>Stories by Maurice Reigman on Medium</title>
            <link>https://medium.com/@mauricereigman?source=rss-d891749bd19b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 07:59:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mauricereigman/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Immutable Typescript classes with Object.copyWith (typesafe)]]></title>
            <link>https://mauricereigman.medium.com/immutable-typescript-classes-with-object-copywith-typesafe-a84fff3971dc?source=rss-d891749bd19b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a84fff3971dc</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Maurice Reigman]]></dc:creator>
            <pubDate>Mon, 17 Jun 2019 20:04:00 GMT</pubDate>
            <atom:updated>2021-01-13T08:13:25.052Z</atom:updated>
            <content:encoded><![CDATA[<h3>Typesafe immutable classes with Typescript (Object.copyWith())</h3><h4>In functional programming immutability plays a big part. Not modifying state and working with pure functions leads to code that is easier to read and is less prone to error.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D37mDzbvWOE2Ro9Yx9M13w.png" /></figure><p>Javascript has had many FP libraries like ImmutableJs or Ramda that provide us with immutability. We can now even have native immutability with methods like Object.freeze and the spread operator. While al these methods are great i found i was still missing an elegant way to implement class based immutability. I went looking for one and thought i’d share my results.</p><pre><em>class </em>Car {<br>   <em>constructor</em>(<br>      <em>public readonly </em>wheels: <em>number</em>,<br>      <em>public readonly </em>topSpeed: <em>number</em>,<br>      <em>public readonly </em>name: <em>string</em>,<br>      <em>public readonly </em>isComfortable: <em>boolean</em>) {<br>   }<br>}</pre><p>Thanks to typescript we can add <strong>readonly</strong> modifiers to our class properties. This helps a lot since we get errors at compile time which IntelliSense can pick up. The problem is that with immutability we still have the need to change an objects properties. We do this by creating a new Object instance with all of the existing objects values plus some modifications. So how do we do this in an elegant way. Let’s go through some wel known native ways to do this.</p><h3>spread operator:</h3><pre><em>const </em>myCar = <em>new </em>Car(4, 200, &#39;supercar&#39;, <em>true</em>);<br><em>const </em>modifiedCar = {...myCar, wheels: 3};</pre><p><strong>the problem:</strong><br>The spread operator is an easy and readable way to do this. It has one major caveat that it removes the constructor.prototype of the object and makes it a plain javascript Object type. This is a problem if you were to do any <strong>instanceof</strong> or <strong>typeof</strong> checks.</p><pre><em>const </em>result = modifiedCar <em>instanceof </em>Car;<br><em>// is false</em></pre><h3>Object.assign:</h3><pre>const myCar = new Car(4, 200, &#39;supercar&#39;, true);<br>const modifiedCar = Object.assign(Object.create(myCar), {wheels: 3});<br>const result = modifiedCar instanceof Car;<br>// is true</pre><p>This already is much better. The prototype stays in tact and it’s pretty readable.</p><p>But how nice would it be to have this functionality on the object itself. Take for instance a <strong>Scala case class</strong> or K<strong>otlins data class</strong> which on default have a “.copy(modifications)” method.</p><pre>car.copy(wheels = 3)</pre><p>This takes it to a new level. Being as descriptive as can be and having the advantage of being a method which is easily found when typing in “car.” (since pretty much all modern IDE’s will list all available methods of an object with their corresponding arguments when you type the dot).</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*XCyTSXTbOdxYFSxhXkbFIg.png" /></figure><p>let’s see if we can do this in Typescript by taking our last example and combining it with scala’s case class copy method.</p><h3>solution:</h3><pre>class Car {<br>   constructor(<br>      public readonly wheels: number,<br>      public readonly topSpeed: number,<br>      public readonly name: string,<br>      public readonly isComfortable: boolean) {<br>   }</pre><pre>   public copyWith(modifyObject: { [P in keyof Car]?: Car[P] }): Car {<br>      return Object.assign(Object.create(Car.prototype), { ...this, ...modifyObject });<br>   }<br>}<br>const myCar = new Car(4, 200, &#39;supercar&#39;, true);<br>const modifiedCar = myCar.copyWith({wheels: 3});</pre><p><strong>PERFECT! easily accessible, descriptive and most of all typesafe!</strong></p><ul><li>If we were to give the modify method an object with a non existing property on the Car prototype it would not compile</li><li>if we were to give the modify method an object with a property that does exist on the Car prototype but give it a wrong type e.g string instead of number it would not compile</li></ul><p>We can further improve this by making it more generic:</p><h3>Generic solution:</h3><pre><em>class </em>ObjectCopier {<br>   <em>public </em>copyWith(modifyObject: { [P <em>in keyof this</em>]?: <em>this</em>[P] }): <em>this </em>{<br>      <em>return </em>Object.assign(Object.create(<em>this</em>.constructor.prototype), { ...<em>this</em>, ...modifyObject });<br>   }<br>}</pre><pre><em>class </em>Car <em>extends </em>ObjectCopier {<br>   <em>constructor</em>(<br>      <em>public readonly </em>wheels: <em>number</em>,<br>      <em>public readonly </em>topSpeed: <em>number</em>,<br>      <em>public readonly </em>name: <em>string</em>,<br>      <em>public readonly </em>isComfortable: <em>boolean</em>) {<br>      <em>super</em>();<br>   }<br>}</pre><pre><em>const </em>myCar = <em>new </em>Car(4, 200, &#39;my car&#39;, <em>true</em>);</pre><pre>myCar.copyWith({wheels: 3});</pre><p><a href="https://repl.it/@MauriceReigman/SlightForcefulProgrammingtool#index.ts">working example here</a></p><p>The ObjectCopier can now be extended by every class or could (while i havent tested this yet) even be implemented as a mixin if one would like composition over inheritance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a84fff3971dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>