title: TypeScript: Copy Map while adding a key-value-pair at the same time
body: <p>I want to elegantly copy a typescript struct <code>interfaceName</code> (which satisfies a certain interface). This TypeScript contains a map <code>attribute3</code> of Type <code>Map&lt;IKey, number&gt;</code>, which perhaps has to be modified (depending on a condition): An additional key value pair has to be inserted.</p>
  
  <p><code>IKey</code>, again, is an interface. </p>
  
  <pre><code>interface InterfaceName{
     attribute1: string
     attribute2: string
     attribute3: Map&lt;IKey, number&gt;
  </code></pre>
  
  <p>}</p>
  
  <pre><code>interface IKey{
      a1: number
      a2: number
  }
  </code></pre>
  
  <p>}</p>
  
  <p>My attempt was the following: I just use the <code>...</code> syntax to copy all the members of <code>interfaceName</code> and then try to assign <code>attribute3</code> a modified copy.
  But somehow this does not work: In the end the same Map object is passed out of the function, regardless of the boolean.</p>
  
  <pre><code>const createModifiedCopyIfWished = (interfaceName: InterfaceName, wished: Boolean) =&gt; wished ? {
          ...interfaceName,
          attribute3: interfaceName.attribute3.set({a1:1,a2:2},5)
      }
      :
      interfaceName
  
  let a: InterfaceName = {
      attribute1: "a",
      attribute2: "b",
      attribute3: new Map&lt;IKey, number&gt;()
  }
  
  let b = createModifiedCopyIfWished(a, true)
  
  // {"attribute1":"a","attribute2":"b","attribute3":{}}
  console.log(JSON.stringify(b))
  </code></pre>
  
  <p>What is the prober way to do this?
  Is it even possible within one statement?</p>
  
  <p>Working example: <a href="http://www.typescriptlang.org/play/#src=interface%20InterfaceName%20%7B%0D%0A%20%20%20%20attribute1%3A%20string%0D%0A%20%20%20%20attribute2%3A%20string%0D%0A%20%20%20%20attribute3%3A%20Map%3CIKey%2C%20number%3E%0D%0A%7D%0D%0A%0D%0Ainterface%20IKey%7B%0D%0A%20%20%20%20a1%3A%20number%0D%0A%20%20%20%20a2%3A%20number%0D%0A%7D%0D%0A%0D%0Aconst%20createModifiedCopyIfWished%20%3D%20(interfaceName%3A%20InterfaceName%2C%20wished%3A%20Boolean)%20%3D%3E%20wished%20%3F%20%7B%0D%0A%20%20%20%20%20%20%20%20...interfaceName%2C%0D%0A%20%20%20%20%20%20%20%20attribute3%3A%20new%20Map(interfaceName.attribute3).set(%7B%20a1%3A%201%2C%20a2%3A%202%20%7D%2C%20123)%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20%3A%0D%0A%20%20%20%20interfaceName%0D%0A%0D%0A%0D%0Alet%20a%3A%20InterfaceName%20%3D%20%7B%0D%0A%20%20%20%20attribute1%3A%20%22a%22%2C%0D%0A%20%20%20%20attribute2%3A%20%22b%22%2C%0D%0A%20%20%20%20attribute3%3A%20new%20Map%3CIKey%2C%20number%3E()%0D%0A%7D%0D%0A%0D%0Alet%20b%20%3D%20createModifiedCopyIfWished(a%2C%20true)%0D%0A%0D%0A%2F%2F%20%7B%22attribute1%22%3A%22a%22%2C%22attribute2%22%3A%22b%22%2C%22attribute3%22%3A%7B%7D%7D%0D%0Aconsole.log(JSON.stringify(b))" rel="nofollow noreferrer">LiveCode</a></p>