title: typescript interface: optional but not undefined
body: <p>How can I describe type like </p>
  
  <blockquote>
    <p>key is optional, but if it existed, it cannot be undefined.</p>
  </blockquote>
  
  <p>At the first time, I'm using Partial to make all properties of T optional. </p>
  
  <pre class="lang-js prettyprint-override"><code>interface A {
    a: number;
  }
  
  var data: A = {
    a: 1,
  }
  
  var update1: Partial&lt;A&gt; = {
  
  }
  
  var update2: Partial&lt;A&gt; = {
    a: undefined
  }
  
  var result1: A = {
    ...data,
    ...update1,
  } // { a: 1 }
  
  var result2: A = {
    ...data,
    ...update2,
  } // { a: undefined }
  </code></pre>
  
  <p>The problem here is that result2 is not implementing interface A in runtime, but typescript never complains about it. Is it bug or feature?
  I guess typescript not working well with spread operator...</p>
  
  <p>The goal is distinguish these two variable using typescript!</p>
  
  <pre class="lang-js prettyprint-override"><code>
  var data: T = {
    a: 1,
    b: 2,
  }
  
  var optional1: MyPartial&lt;T&gt; = { // Totally OK
  
  }
  
  var optional2: MyPartial&lt;T&gt; = { // OK
    a: 3,
  }
  
  var optional3: MyPartial&lt;T&gt; = { // OK
    b: 4,
  }
  
  var optional4: MyPartial&lt;T&gt; = { // OK
    a: 3,
    b: 4,
  }
  
  var undef1: MyPartial&lt;T&gt; = { // typescript must throw error
    a: undefined,
  }
  
  var undef2: MyPartial&lt;T&gt; = { // typescript must throw error
    a: 3,
    b: undefined
  }
  
  ...
  
  </code></pre>
  
  <p>Check this out <a href="http://www.typescriptlang.org/play/#src=%0D%0Ainterface%20A%20%7B%0D%0A%20%20a%3A%20number%3B%0D%0A%7D%0D%0A%0D%0Avar%20data%3A%20A%20%3D%20%7B%0D%0A%20%20a%3A%201%2C%0D%0A%7D%0D%0A%0D%0Avar%20update1%3A%20Partial%3CA%3E%20%3D%20%7B%0D%0A%0D%0A%7D%0D%0A%0D%0Avar%20update2%3A%20Partial%3CA%3E%20%3D%20%7B%0D%0A%20%20a%3A%20undefined%0D%0A%7D%0D%0A%0D%0Avar%20result1%3A%20A%20%3D%20%7B%0D%0A%20%20...data%2C%0D%0A%20%20...update1%2C%0D%0A%7D%0D%0A%0D%0Avar%20result2%3A%20A%20%3D%20%7B%0D%0A%20%20...data%2C%0D%0A%20%20...update2%2C%0D%0A%7D" rel="noreferrer">TypeScript playground example.</a></p>