title: TypeScript type cast
body: <p>I have an object, and I need to add some extra properties to it in some cases.</p>
  
  <pre class="lang-js prettyprint-override"><code>interface Item {
      name: string
  }
  
  function addProp(obj: Item) {
      type WithFoo = Item &amp; { foo?: string; }
  
      // The following does NOT work
      obj = obj as WithFoo;
  
      if (obj.name == 'test') {
          obj.foo = 'hello';
       }
  }
  
  
  </code></pre>
  
  <p>It seems <code>obj = obj as AnotherType</code> does NOT work, but if I assign to another variable, it works, <code>const anotherObj = obj as AnotherType</code>.</p>
  
  <p>Is there any way to cast the <code>type</code>, <strong>without</strong> introducing another variable?</p>
  
  <p>Here is <a href="https://www.typescriptlang.org/play/index.html?ssl=1&amp;ssc=1&amp;pln=13&amp;pc=1#code/JYOwLgpgTgZghgYwgAgJKQLbIN4ChkHIhwYQBcyAzmFKAOa4C+uuMAriAmMAPYjJwAJoIAKUHgAcAFDwBGAKwroIGAJQ58hMAE8JKAOrAwACwBiPHsgC8aTMgBkOZDAsB+CtVog6AbmTNCZDl5ayCFAUpkQxNzHh9NAmAYZBkFADpiUmsbAHJIahz1PEDA4LSXS1zjCAAbGp4c+JLmZlwgA" rel="nofollow noreferrer">online playground</a></p>